three.cjs 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '183dev';
  8. /**
  9. * Represents mouse buttons and interaction types in context of controls.
  10. *
  11. * @type {ConstantsMouse}
  12. * @constant
  13. */
  14. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  15. /**
  16. * Represents touch interaction types in context of controls.
  17. *
  18. * @type {ConstantsTouch}
  19. * @constant
  20. */
  21. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  22. /**
  23. * Disables face culling.
  24. *
  25. * @type {number}
  26. * @constant
  27. */
  28. const CullFaceNone = 0;
  29. /**
  30. * Culls back faces.
  31. *
  32. * @type {number}
  33. * @constant
  34. */
  35. const CullFaceBack = 1;
  36. /**
  37. * Culls front faces.
  38. *
  39. * @type {number}
  40. * @constant
  41. */
  42. const CullFaceFront = 2;
  43. /**
  44. * Culls both front and back faces.
  45. *
  46. * @type {number}
  47. * @constant
  48. */
  49. const CullFaceFrontBack = 3;
  50. /**
  51. * Gives unfiltered shadow maps - fastest, but lowest quality.
  52. *
  53. * @type {number}
  54. * @constant
  55. */
  56. const BasicShadowMap = 0;
  57. /**
  58. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  59. *
  60. * @type {number}
  61. * @constant
  62. */
  63. const PCFShadowMap = 1;
  64. /**
  65. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  66. * better soft shadows especially when using low-resolution shadow maps.
  67. *
  68. * @type {number}
  69. * @constant
  70. */
  71. const PCFSoftShadowMap = 2;
  72. /**
  73. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  74. * When using VSMShadowMap all shadow receivers will also cast shadows.
  75. *
  76. * @type {number}
  77. * @constant
  78. */
  79. const VSMShadowMap = 3;
  80. /**
  81. * Only front faces are rendered.
  82. *
  83. * @type {number}
  84. * @constant
  85. */
  86. const FrontSide = 0;
  87. /**
  88. * Only back faces are rendered.
  89. *
  90. * @type {number}
  91. * @constant
  92. */
  93. const BackSide = 1;
  94. /**
  95. * Both front and back faces are rendered.
  96. *
  97. * @type {number}
  98. * @constant
  99. */
  100. const DoubleSide = 2;
  101. /**
  102. * No blending is performed which effectively disables
  103. * alpha transparency.
  104. *
  105. * @type {number}
  106. * @constant
  107. */
  108. const NoBlending = 0;
  109. /**
  110. * The default blending.
  111. *
  112. * @type {number}
  113. * @constant
  114. */
  115. const NormalBlending = 1;
  116. /**
  117. * Represents additive blending.
  118. *
  119. * @type {number}
  120. * @constant
  121. */
  122. const AdditiveBlending = 2;
  123. /**
  124. * Represents subtractive blending.
  125. *
  126. * @type {number}
  127. * @constant
  128. */
  129. const SubtractiveBlending = 3;
  130. /**
  131. * Represents multiply blending.
  132. *
  133. * @type {number}
  134. * @constant
  135. */
  136. const MultiplyBlending = 4;
  137. /**
  138. * Represents custom blending.
  139. *
  140. * @type {number}
  141. * @constant
  142. */
  143. const CustomBlending = 5;
  144. /**
  145. * Represents material blending.
  146. *
  147. * @type {number}
  148. * @constant
  149. */
  150. const MaterialBlending = 6;
  151. /**
  152. * A `source + destination` blending equation.
  153. *
  154. * @type {number}
  155. * @constant
  156. */
  157. const AddEquation = 100;
  158. /**
  159. * A `source - destination` blending equation.
  160. *
  161. * @type {number}
  162. * @constant
  163. */
  164. const SubtractEquation = 101;
  165. /**
  166. * A `destination - source` blending equation.
  167. *
  168. * @type {number}
  169. * @constant
  170. */
  171. const ReverseSubtractEquation = 102;
  172. /**
  173. * A blend equation that uses the minimum of source and destination.
  174. *
  175. * @type {number}
  176. * @constant
  177. */
  178. const MinEquation = 103;
  179. /**
  180. * A blend equation that uses the maximum of source and destination.
  181. *
  182. * @type {number}
  183. * @constant
  184. */
  185. const MaxEquation = 104;
  186. /**
  187. * Multiplies all colors by `0`.
  188. *
  189. * @type {number}
  190. * @constant
  191. */
  192. const ZeroFactor = 200;
  193. /**
  194. * Multiplies all colors by `1`.
  195. *
  196. * @type {number}
  197. * @constant
  198. */
  199. const OneFactor = 201;
  200. /**
  201. * Multiplies all colors by the source colors.
  202. *
  203. * @type {number}
  204. * @constant
  205. */
  206. const SrcColorFactor = 202;
  207. /**
  208. * Multiplies all colors by `1` minus each source color.
  209. *
  210. * @type {number}
  211. * @constant
  212. */
  213. const OneMinusSrcColorFactor = 203;
  214. /**
  215. * Multiplies all colors by the source alpha value.
  216. *
  217. * @type {number}
  218. * @constant
  219. */
  220. const SrcAlphaFactor = 204;
  221. /**
  222. * Multiplies all colors by 1 minus the source alpha value.
  223. *
  224. * @type {number}
  225. * @constant
  226. */
  227. const OneMinusSrcAlphaFactor = 205;
  228. /**
  229. * Multiplies all colors by the destination alpha value.
  230. *
  231. * @type {number}
  232. * @constant
  233. */
  234. const DstAlphaFactor = 206;
  235. /**
  236. * Multiplies all colors by `1` minus the destination alpha value.
  237. *
  238. * @type {number}
  239. * @constant
  240. */
  241. const OneMinusDstAlphaFactor = 207;
  242. /**
  243. * Multiplies all colors by the destination color.
  244. *
  245. * @type {number}
  246. * @constant
  247. */
  248. const DstColorFactor = 208;
  249. /**
  250. * Multiplies all colors by `1` minus each destination color.
  251. *
  252. * @type {number}
  253. * @constant
  254. */
  255. const OneMinusDstColorFactor = 209;
  256. /**
  257. * Multiplies the RGB colors by the smaller of either the source alpha
  258. * value or the value of `1` minus the destination alpha value. The alpha
  259. * value is multiplied by `1`.
  260. *
  261. * @type {number}
  262. * @constant
  263. */
  264. const SrcAlphaSaturateFactor = 210;
  265. /**
  266. * Multiplies all colors by a constant color.
  267. *
  268. * @type {number}
  269. * @constant
  270. */
  271. const ConstantColorFactor = 211;
  272. /**
  273. * Multiplies all colors by `1` minus a constant color.
  274. *
  275. * @type {number}
  276. * @constant
  277. */
  278. const OneMinusConstantColorFactor = 212;
  279. /**
  280. * Multiplies all colors by a constant alpha value.
  281. *
  282. * @type {number}
  283. * @constant
  284. */
  285. const ConstantAlphaFactor = 213;
  286. /**
  287. * Multiplies all colors by 1 minus a constant alpha value.
  288. *
  289. * @type {number}
  290. * @constant
  291. */
  292. const OneMinusConstantAlphaFactor = 214;
  293. /**
  294. * Never pass.
  295. *
  296. * @type {number}
  297. * @constant
  298. */
  299. const NeverDepth = 0;
  300. /**
  301. * Always pass.
  302. *
  303. * @type {number}
  304. * @constant
  305. */
  306. const AlwaysDepth = 1;
  307. /**
  308. * Pass if the incoming value is less than the depth buffer value.
  309. *
  310. * @type {number}
  311. * @constant
  312. */
  313. const LessDepth = 2;
  314. /**
  315. * Pass if the incoming value is less than or equal to the depth buffer value.
  316. *
  317. * @type {number}
  318. * @constant
  319. */
  320. const LessEqualDepth = 3;
  321. /**
  322. * Pass if the incoming value equals the depth buffer value.
  323. *
  324. * @type {number}
  325. * @constant
  326. */
  327. const EqualDepth = 4;
  328. /**
  329. * Pass if the incoming value is greater than or equal to the depth buffer value.
  330. *
  331. * @type {number}
  332. * @constant
  333. */
  334. const GreaterEqualDepth = 5;
  335. /**
  336. * Pass if the incoming value is greater than the depth buffer value.
  337. *
  338. * @type {number}
  339. * @constant
  340. */
  341. const GreaterDepth = 6;
  342. /**
  343. * Pass if the incoming value is not equal to the depth buffer value.
  344. *
  345. * @type {number}
  346. * @constant
  347. */
  348. const NotEqualDepth = 7;
  349. /**
  350. * Multiplies the environment map color with the surface color.
  351. *
  352. * @type {number}
  353. * @constant
  354. */
  355. const MultiplyOperation = 0;
  356. /**
  357. * Uses reflectivity to blend between the two colors.
  358. *
  359. * @type {number}
  360. * @constant
  361. */
  362. const MixOperation = 1;
  363. /**
  364. * Adds the two colors.
  365. *
  366. * @type {number}
  367. * @constant
  368. */
  369. const AddOperation = 2;
  370. /**
  371. * No tone mapping is applied.
  372. *
  373. * @type {number}
  374. * @constant
  375. */
  376. const NoToneMapping = 0;
  377. /**
  378. * Linear tone mapping.
  379. *
  380. * @type {number}
  381. * @constant
  382. */
  383. const LinearToneMapping = 1;
  384. /**
  385. * Reinhard tone mapping.
  386. *
  387. * @type {number}
  388. * @constant
  389. */
  390. const ReinhardToneMapping = 2;
  391. /**
  392. * Cineon tone mapping.
  393. *
  394. * @type {number}
  395. * @constant
  396. */
  397. const CineonToneMapping = 3;
  398. /**
  399. * ACES Filmic tone mapping.
  400. *
  401. * @type {number}
  402. * @constant
  403. */
  404. const ACESFilmicToneMapping = 4;
  405. /**
  406. * Custom tone mapping.
  407. *
  408. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  409. *
  410. * @type {number}
  411. * @constant
  412. */
  413. const CustomToneMapping = 5;
  414. /**
  415. * AgX tone mapping.
  416. *
  417. * @type {number}
  418. * @constant
  419. */
  420. const AgXToneMapping = 6;
  421. /**
  422. * Neutral tone mapping.
  423. *
  424. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  425. *
  426. * @type {number}
  427. * @constant
  428. */
  429. const NeutralToneMapping = 7;
  430. /**
  431. * The skinned mesh shares the same world space as the skeleton.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const AttachedBindMode = 'attached';
  437. /**
  438. * The skinned mesh does not share the same world space as the skeleton.
  439. * This is useful when a skeleton is shared across multiple skinned meshes.
  440. *
  441. * @type {string}
  442. * @constant
  443. */
  444. const DetachedBindMode = 'detached';
  445. /**
  446. * Maps textures using the geometry's UV coordinates.
  447. *
  448. * @type {number}
  449. * @constant
  450. */
  451. const UVMapping = 300;
  452. /**
  453. * Reflection mapping for cube textures.
  454. *
  455. * @type {number}
  456. * @constant
  457. */
  458. const CubeReflectionMapping = 301;
  459. /**
  460. * Refraction mapping for cube textures.
  461. *
  462. * @type {number}
  463. * @constant
  464. */
  465. const CubeRefractionMapping = 302;
  466. /**
  467. * Reflection mapping for equirectangular textures.
  468. *
  469. * @type {number}
  470. * @constant
  471. */
  472. const EquirectangularReflectionMapping = 303;
  473. /**
  474. * Refraction mapping for equirectangular textures.
  475. *
  476. * @type {number}
  477. * @constant
  478. */
  479. const EquirectangularRefractionMapping = 304;
  480. /**
  481. * Reflection mapping for PMREM textures.
  482. *
  483. * @type {number}
  484. * @constant
  485. */
  486. const CubeUVReflectionMapping = 306;
  487. /**
  488. * The texture will simply repeat to infinity.
  489. *
  490. * @type {number}
  491. * @constant
  492. */
  493. const RepeatWrapping = 1000;
  494. /**
  495. * The last pixel of the texture stretches to the edge of the mesh.
  496. *
  497. * @type {number}
  498. * @constant
  499. */
  500. const ClampToEdgeWrapping = 1001;
  501. /**
  502. * The texture will repeats to infinity, mirroring on each repeat.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const MirroredRepeatWrapping = 1002;
  508. /**
  509. * Returns the value of the texture element that is nearest (in Manhattan distance)
  510. * to the specified texture coordinates.
  511. *
  512. * @type {number}
  513. * @constant
  514. */
  515. const NearestFilter = 1003;
  516. /**
  517. * Chooses the mipmap that most closely matches the size of the pixel being textured
  518. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  519. * to produce a texture value.
  520. *
  521. * @type {number}
  522. * @constant
  523. */
  524. const NearestMipmapNearestFilter = 1004;
  525. const NearestMipMapNearestFilter = 1004; // legacy
  526. /**
  527. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  528. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  529. * The final texture value is a weighted average of those two values.
  530. *
  531. * @type {number}
  532. * @constant
  533. */
  534. const NearestMipmapLinearFilter = 1005;
  535. const NearestMipMapLinearFilter = 1005; // legacy
  536. /**
  537. * Returns the weighted average of the four texture elements that are closest to the specified
  538. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  539. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  540. *
  541. * @type {number}
  542. * @constant
  543. */
  544. const LinearFilter = 1006;
  545. /**
  546. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  547. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  548. * center of the pixel) to produce a texture value.
  549. *
  550. * @type {number}
  551. * @constant
  552. */
  553. const LinearMipmapNearestFilter = 1007;
  554. const LinearMipMapNearestFilter = 1007; // legacy
  555. /**
  556. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  557. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  558. * is a weighted average of those two values.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const LinearMipmapLinearFilter = 1008;
  564. const LinearMipMapLinearFilter = 1008; // legacy
  565. /**
  566. * An unsigned byte data type for textures.
  567. *
  568. * @type {number}
  569. * @constant
  570. */
  571. const UnsignedByteType = 1009;
  572. /**
  573. * A byte data type for textures.
  574. *
  575. * @type {number}
  576. * @constant
  577. */
  578. const ByteType = 1010;
  579. /**
  580. * A short data type for textures.
  581. *
  582. * @type {number}
  583. * @constant
  584. */
  585. const ShortType = 1011;
  586. /**
  587. * An unsigned short data type for textures.
  588. *
  589. * @type {number}
  590. * @constant
  591. */
  592. const UnsignedShortType = 1012;
  593. /**
  594. * An int data type for textures.
  595. *
  596. * @type {number}
  597. * @constant
  598. */
  599. const IntType = 1013;
  600. /**
  601. * An unsigned int data type for textures.
  602. *
  603. * @type {number}
  604. * @constant
  605. */
  606. const UnsignedIntType = 1014;
  607. /**
  608. * A float data type for textures.
  609. *
  610. * @type {number}
  611. * @constant
  612. */
  613. const FloatType = 1015;
  614. /**
  615. * A half float data type for textures.
  616. *
  617. * @type {number}
  618. * @constant
  619. */
  620. const HalfFloatType = 1016;
  621. /**
  622. * An unsigned short 4_4_4_4 (packed) data type for textures.
  623. *
  624. * @type {number}
  625. * @constant
  626. */
  627. const UnsignedShort4444Type = 1017;
  628. /**
  629. * An unsigned short 5_5_5_1 (packed) data type for textures.
  630. *
  631. * @type {number}
  632. * @constant
  633. */
  634. const UnsignedShort5551Type = 1018;
  635. /**
  636. * An unsigned int 24_8 data type for textures.
  637. *
  638. * @type {number}
  639. * @constant
  640. */
  641. const UnsignedInt248Type = 1020;
  642. /**
  643. * An unsigned int 5_9_9_9 (packed) data type for textures.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const UnsignedInt5999Type = 35902;
  649. /**
  650. * An unsigned int 10_11_11 (packed) data type for textures.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const UnsignedInt101111Type = 35899;
  656. /**
  657. * Discards the red, green and blue components and reads just the alpha component.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const AlphaFormat = 1021;
  663. /**
  664. * Discards the alpha component and reads the red, green and blue component.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const RGBFormat = 1022;
  670. /**
  671. * Reads the red, green, blue and alpha components.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const RGBAFormat = 1023;
  677. /**
  678. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const DepthFormat = 1026;
  684. /**
  685. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  686. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const DepthStencilFormat = 1027;
  692. /**
  693. * Discards the green, blue and alpha components and reads just the red component.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RedFormat = 1028;
  699. /**
  700. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RedIntegerFormat = 1029;
  706. /**
  707. * Discards the alpha, and blue components and reads the red, and green components.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGFormat = 1030;
  713. /**
  714. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGIntegerFormat = 1031;
  720. /**
  721. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGBIntegerFormat = 1032;
  727. /**
  728. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGBAIntegerFormat = 1033;
  734. /**
  735. * A DXT1-compressed image in an RGB image format.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGB_S3TC_DXT1_Format = 33776;
  741. /**
  742. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT1_Format = 33777;
  748. /**
  749. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGBA_S3TC_DXT3_Format = 33778;
  755. /**
  756. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  757. * compression in how the alpha compression is done.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGBA_S3TC_DXT5_Format = 33779;
  763. /**
  764. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGB_PVRTC_4BPPV1_Format = 35840;
  770. /**
  771. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGB_PVRTC_2BPPV1_Format = 35841;
  777. /**
  778. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGBA_PVRTC_4BPPV1_Format = 35842;
  784. /**
  785. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGBA_PVRTC_2BPPV1_Format = 35843;
  791. /**
  792. * ETC1 RGB format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGB_ETC1_Format = 36196;
  798. /**
  799. * ETC2 RGB format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGB_ETC2_Format = 37492;
  805. /**
  806. * ETC2 RGBA format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const RGBA_ETC2_EAC_Format = 37496;
  812. /**
  813. * EAC R11 UNORM format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const R11_EAC_Format = 37488; // 0x9270
  819. /**
  820. * EAC R11 SNORM format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  826. /**
  827. * EAC RG11 UNORM format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const RG11_EAC_Format = 37490; // 0x9272
  833. /**
  834. * EAC RG11 SNORM format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  840. /**
  841. * ASTC RGBA 4x4 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_4x4_Format = 37808;
  847. /**
  848. * ASTC RGBA 5x4 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_5x4_Format = 37809;
  854. /**
  855. * ASTC RGBA 5x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_5x5_Format = 37810;
  861. /**
  862. * ASTC RGBA 6x5 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_6x5_Format = 37811;
  868. /**
  869. * ASTC RGBA 6x6 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_6x6_Format = 37812;
  875. /**
  876. * ASTC RGBA 8x5 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_8x5_Format = 37813;
  882. /**
  883. * ASTC RGBA 8x6 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_8x6_Format = 37814;
  889. /**
  890. * ASTC RGBA 8x8 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_8x8_Format = 37815;
  896. /**
  897. * ASTC RGBA 10x5 format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_ASTC_10x5_Format = 37816;
  903. /**
  904. * ASTC RGBA 10x6 format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGBA_ASTC_10x6_Format = 37817;
  910. /**
  911. * ASTC RGBA 10x8 format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGBA_ASTC_10x8_Format = 37818;
  917. /**
  918. * ASTC RGBA 10x10 format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RGBA_ASTC_10x10_Format = 37819;
  924. /**
  925. * ASTC RGBA 12x10 format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const RGBA_ASTC_12x10_Format = 37820;
  931. /**
  932. * ASTC RGBA 12x12 format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RGBA_ASTC_12x12_Format = 37821;
  938. /**
  939. * BPTC RGBA format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const RGBA_BPTC_Format = 36492;
  945. /**
  946. * BPTC Signed RGB format.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const RGB_BPTC_SIGNED_Format = 36494;
  952. /**
  953. * BPTC Unsigned RGB format.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const RGB_BPTC_UNSIGNED_Format = 36495;
  959. /**
  960. * RGTC1 Red format.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const RED_RGTC1_Format = 36283;
  966. /**
  967. * RGTC1 Signed Red format.
  968. *
  969. * @type {number}
  970. * @constant
  971. */
  972. const SIGNED_RED_RGTC1_Format = 36284;
  973. /**
  974. * RGTC2 Red Green format.
  975. *
  976. * @type {number}
  977. * @constant
  978. */
  979. const RED_GREEN_RGTC2_Format = 36285;
  980. /**
  981. * RGTC2 Signed Red Green format.
  982. *
  983. * @type {number}
  984. * @constant
  985. */
  986. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  987. /**
  988. * Animations are played once.
  989. *
  990. * @type {number}
  991. * @constant
  992. */
  993. const LoopOnce = 2200;
  994. /**
  995. * Animations are played with a chosen number of repetitions, each time jumping from
  996. * the end of the clip directly to its beginning.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const LoopRepeat = 2201;
  1002. /**
  1003. * Animations are played with a chosen number of repetitions, alternately playing forward
  1004. * and backward.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const LoopPingPong = 2202;
  1010. /**
  1011. * Discrete interpolation mode for keyframe tracks.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const InterpolateDiscrete = 2300;
  1017. /**
  1018. * Linear interpolation mode for keyframe tracks.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const InterpolateLinear = 2301;
  1024. /**
  1025. * Smooth interpolation mode for keyframe tracks.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const InterpolateSmooth = 2302;
  1031. /**
  1032. * Bezier interpolation mode for keyframe tracks.
  1033. *
  1034. * Uses cubic Bezier curves with explicit 2D control points.
  1035. * Requires tangent data to be set on the track.
  1036. *
  1037. * @type {number}
  1038. * @constant
  1039. */
  1040. const InterpolateBezier = 2303;
  1041. /**
  1042. * Zero curvature ending for animations.
  1043. *
  1044. * @type {number}
  1045. * @constant
  1046. */
  1047. const ZeroCurvatureEnding = 2400;
  1048. /**
  1049. * Zero slope ending for animations.
  1050. *
  1051. * @type {number}
  1052. * @constant
  1053. */
  1054. const ZeroSlopeEnding = 2401;
  1055. /**
  1056. * Wrap around ending for animations.
  1057. *
  1058. * @type {number}
  1059. * @constant
  1060. */
  1061. const WrapAroundEnding = 2402;
  1062. /**
  1063. * Default animation blend mode.
  1064. *
  1065. * @type {number}
  1066. * @constant
  1067. */
  1068. const NormalAnimationBlendMode = 2500;
  1069. /**
  1070. * Additive animation blend mode. Can be used to layer motions on top of
  1071. * each other to build complex performances from smaller re-usable assets.
  1072. *
  1073. * @type {number}
  1074. * @constant
  1075. */
  1076. const AdditiveAnimationBlendMode = 2501;
  1077. /**
  1078. * For every three vertices draw a single triangle.
  1079. *
  1080. * @type {number}
  1081. * @constant
  1082. */
  1083. const TrianglesDrawMode = 0;
  1084. /**
  1085. * For each vertex draw a triangle from the last three vertices.
  1086. *
  1087. * @type {number}
  1088. * @constant
  1089. */
  1090. const TriangleStripDrawMode = 1;
  1091. /**
  1092. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1093. *
  1094. * @type {number}
  1095. * @constant
  1096. */
  1097. const TriangleFanDrawMode = 2;
  1098. /**
  1099. * The depth value is inverted (1.0 - z) for visualization purposes.
  1100. *
  1101. * @type {number}
  1102. * @constant
  1103. */
  1104. const BasicDepthPacking = 3200;
  1105. /**
  1106. * The depth value is packed into 32 bit RGBA.
  1107. *
  1108. * @type {number}
  1109. * @constant
  1110. */
  1111. const RGBADepthPacking = 3201;
  1112. /**
  1113. * The depth value is packed into 24 bit RGB.
  1114. *
  1115. * @type {number}
  1116. * @constant
  1117. */
  1118. const RGBDepthPacking = 3202;
  1119. /**
  1120. * The depth value is packed into 16 bit RG.
  1121. *
  1122. * @type {number}
  1123. * @constant
  1124. */
  1125. const RGDepthPacking = 3203;
  1126. /**
  1127. * Normal information is relative to the underlying surface.
  1128. *
  1129. * @type {number}
  1130. * @constant
  1131. */
  1132. const TangentSpaceNormalMap = 0;
  1133. /**
  1134. * Normal information is relative to the object orientation.
  1135. *
  1136. * @type {number}
  1137. * @constant
  1138. */
  1139. const ObjectSpaceNormalMap = 1;
  1140. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1141. /**
  1142. * No color space.
  1143. *
  1144. * @type {string}
  1145. * @constant
  1146. */
  1147. const NoColorSpace = '';
  1148. /**
  1149. * sRGB color space.
  1150. *
  1151. * @type {string}
  1152. * @constant
  1153. */
  1154. const SRGBColorSpace = 'srgb';
  1155. /**
  1156. * sRGB-linear color space.
  1157. *
  1158. * @type {string}
  1159. * @constant
  1160. */
  1161. const LinearSRGBColorSpace = 'srgb-linear';
  1162. /**
  1163. * Linear transfer function.
  1164. *
  1165. * @type {string}
  1166. * @constant
  1167. */
  1168. const LinearTransfer = 'linear';
  1169. /**
  1170. * sRGB transfer function.
  1171. *
  1172. * @type {string}
  1173. * @constant
  1174. */
  1175. const SRGBTransfer = 'srgb';
  1176. /**
  1177. * No normal map packing.
  1178. *
  1179. * @type {string}
  1180. * @constant
  1181. */
  1182. const NoNormalPacking = '';
  1183. /**
  1184. * Normal RG packing.
  1185. *
  1186. * @type {string}
  1187. * @constant
  1188. */
  1189. const NormalRGPacking = 'rg';
  1190. /**
  1191. * Normal GA packing.
  1192. *
  1193. * @type {string}
  1194. * @constant
  1195. */
  1196. const NormalGAPacking = 'ga';
  1197. /**
  1198. * Sets the stencil buffer value to `0`.
  1199. *
  1200. * @type {number}
  1201. * @constant
  1202. */
  1203. const ZeroStencilOp = 0;
  1204. /**
  1205. * Keeps the current value.
  1206. *
  1207. * @type {number}
  1208. * @constant
  1209. */
  1210. const KeepStencilOp = 7680;
  1211. /**
  1212. * Sets the stencil buffer value to the specified reference value.
  1213. *
  1214. * @type {number}
  1215. * @constant
  1216. */
  1217. const ReplaceStencilOp = 7681;
  1218. /**
  1219. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1220. *
  1221. * @type {number}
  1222. * @constant
  1223. */
  1224. const IncrementStencilOp = 7682;
  1225. /**
  1226. * Decrements the current stencil buffer value. Clamps to `0`.
  1227. *
  1228. * @type {number}
  1229. * @constant
  1230. */
  1231. const DecrementStencilOp = 7683;
  1232. /**
  1233. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1234. * the maximum representable unsigned value.
  1235. *
  1236. * @type {number}
  1237. * @constant
  1238. */
  1239. const IncrementWrapStencilOp = 34055;
  1240. /**
  1241. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1242. * unsigned value when decrementing a stencil buffer value of `0`.
  1243. *
  1244. * @type {number}
  1245. * @constant
  1246. */
  1247. const DecrementWrapStencilOp = 34056;
  1248. /**
  1249. * Inverts the current stencil buffer value bitwise.
  1250. *
  1251. * @type {number}
  1252. * @constant
  1253. */
  1254. const InvertStencilOp = 5386;
  1255. /**
  1256. * Will never return true.
  1257. *
  1258. * @type {number}
  1259. * @constant
  1260. */
  1261. const NeverStencilFunc = 512;
  1262. /**
  1263. * Will return true if the stencil reference value is less than the current stencil value.
  1264. *
  1265. * @type {number}
  1266. * @constant
  1267. */
  1268. const LessStencilFunc = 513;
  1269. /**
  1270. * Will return true if the stencil reference value is equal to the current stencil value.
  1271. *
  1272. * @type {number}
  1273. * @constant
  1274. */
  1275. const EqualStencilFunc = 514;
  1276. /**
  1277. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1278. *
  1279. * @type {number}
  1280. * @constant
  1281. */
  1282. const LessEqualStencilFunc = 515;
  1283. /**
  1284. * Will return true if the stencil reference value is greater than the current stencil value.
  1285. *
  1286. * @type {number}
  1287. * @constant
  1288. */
  1289. const GreaterStencilFunc = 516;
  1290. /**
  1291. * Will return true if the stencil reference value is not equal to the current stencil value.
  1292. *
  1293. * @type {number}
  1294. * @constant
  1295. */
  1296. const NotEqualStencilFunc = 517;
  1297. /**
  1298. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1299. *
  1300. * @type {number}
  1301. * @constant
  1302. */
  1303. const GreaterEqualStencilFunc = 518;
  1304. /**
  1305. * Will always return true.
  1306. *
  1307. * @type {number}
  1308. * @constant
  1309. */
  1310. const AlwaysStencilFunc = 519;
  1311. /**
  1312. * Never pass.
  1313. *
  1314. * @type {number}
  1315. * @constant
  1316. */
  1317. const NeverCompare = 512;
  1318. /**
  1319. * Pass if the incoming value is less than the texture value.
  1320. *
  1321. * @type {number}
  1322. * @constant
  1323. */
  1324. const LessCompare = 513;
  1325. /**
  1326. * Pass if the incoming value equals the texture value.
  1327. *
  1328. * @type {number}
  1329. * @constant
  1330. */
  1331. const EqualCompare = 514;
  1332. /**
  1333. * Pass if the incoming value is less than or equal to the texture value.
  1334. *
  1335. * @type {number}
  1336. * @constant
  1337. */
  1338. const LessEqualCompare = 515;
  1339. /**
  1340. * Pass if the incoming value is greater than the texture value.
  1341. *
  1342. * @type {number}
  1343. * @constant
  1344. */
  1345. const GreaterCompare = 516;
  1346. /**
  1347. * Pass if the incoming value is not equal to the texture value.
  1348. *
  1349. * @type {number}
  1350. * @constant
  1351. */
  1352. const NotEqualCompare = 517;
  1353. /**
  1354. * Pass if the incoming value is greater than or equal to the texture value.
  1355. *
  1356. * @type {number}
  1357. * @constant
  1358. */
  1359. const GreaterEqualCompare = 518;
  1360. /**
  1361. * Always pass.
  1362. *
  1363. * @type {number}
  1364. * @constant
  1365. */
  1366. const AlwaysCompare = 519;
  1367. /**
  1368. * The contents are intended to be specified once by the application, and used many
  1369. * times as the source for drawing and image specification commands.
  1370. *
  1371. * @type {number}
  1372. * @constant
  1373. */
  1374. const StaticDrawUsage = 35044;
  1375. /**
  1376. * The contents are intended to be respecified repeatedly by the application, and
  1377. * used many times as the source for drawing and image specification commands.
  1378. *
  1379. * @type {number}
  1380. * @constant
  1381. */
  1382. const DynamicDrawUsage = 35048;
  1383. /**
  1384. * The contents are intended to be specified once by the application, and used at most
  1385. * a few times as the source for drawing and image specification commands.
  1386. *
  1387. * @type {number}
  1388. * @constant
  1389. */
  1390. const StreamDrawUsage = 35040;
  1391. /**
  1392. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1393. * many times by the application.
  1394. *
  1395. * @type {number}
  1396. * @constant
  1397. */
  1398. const StaticReadUsage = 35045;
  1399. /**
  1400. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1401. * many times by the application.
  1402. *
  1403. * @type {number}
  1404. * @constant
  1405. */
  1406. const DynamicReadUsage = 35049;
  1407. /**
  1408. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1409. * a few times by the application
  1410. *
  1411. * @type {number}
  1412. * @constant
  1413. */
  1414. const StreamReadUsage = 35041;
  1415. /**
  1416. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1417. * the source for WebGL drawing and image specification commands.
  1418. *
  1419. * @type {number}
  1420. * @constant
  1421. */
  1422. const StaticCopyUsage = 35046;
  1423. /**
  1424. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1425. * as the source for WebGL drawing and image specification commands.
  1426. *
  1427. * @type {number}
  1428. * @constant
  1429. */
  1430. const DynamicCopyUsage = 35050;
  1431. /**
  1432. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1433. * as the source for WebGL drawing and image specification commands.
  1434. *
  1435. * @type {number}
  1436. * @constant
  1437. */
  1438. const StreamCopyUsage = 35042;
  1439. /**
  1440. * GLSL 1 shader code.
  1441. *
  1442. * @type {string}
  1443. * @constant
  1444. */
  1445. const GLSL1 = '100';
  1446. /**
  1447. * GLSL 3 shader code.
  1448. *
  1449. * @type {string}
  1450. * @constant
  1451. */
  1452. const GLSL3 = '300 es';
  1453. /**
  1454. * WebGL coordinate system.
  1455. *
  1456. * @type {number}
  1457. * @constant
  1458. */
  1459. const WebGLCoordinateSystem = 2000;
  1460. /**
  1461. * WebGPU coordinate system.
  1462. *
  1463. * @type {number}
  1464. * @constant
  1465. */
  1466. const WebGPUCoordinateSystem = 2001;
  1467. /**
  1468. * Represents the different timestamp query types.
  1469. *
  1470. * @type {ConstantsTimestampQuery}
  1471. * @constant
  1472. */
  1473. const TimestampQuery = {
  1474. COMPUTE: 'compute',
  1475. RENDER: 'render'
  1476. };
  1477. /**
  1478. * Represents mouse buttons and interaction types in context of controls.
  1479. *
  1480. * @type {ConstantsInterpolationSamplingType}
  1481. * @constant
  1482. */
  1483. const InterpolationSamplingType = {
  1484. PERSPECTIVE: 'perspective',
  1485. LINEAR: 'linear',
  1486. FLAT: 'flat'
  1487. };
  1488. /**
  1489. * Represents the different interpolation sampling modes.
  1490. *
  1491. * @type {ConstantsInterpolationSamplingMode}
  1492. * @constant
  1493. */
  1494. const InterpolationSamplingMode = {
  1495. NORMAL: 'normal',
  1496. CENTROID: 'centroid',
  1497. SAMPLE: 'sample',
  1498. FIRST: 'first',
  1499. EITHER: 'either'
  1500. };
  1501. /**
  1502. * Compatibility flags for features that may not be supported across all platforms.
  1503. *
  1504. * @type {Object}
  1505. * @constant
  1506. */
  1507. const Compatibility = {
  1508. TEXTURE_COMPARE: 'depthTextureCompare'
  1509. };
  1510. /**
  1511. * This type represents mouse buttons and interaction types in context of controls.
  1512. *
  1513. * @typedef {Object} ConstantsMouse
  1514. * @property {number} MIDDLE - The left mouse button.
  1515. * @property {number} LEFT - The middle mouse button.
  1516. * @property {number} RIGHT - The right mouse button.
  1517. * @property {number} ROTATE - A rotate interaction.
  1518. * @property {number} DOLLY - A dolly interaction.
  1519. * @property {number} PAN - A pan interaction.
  1520. **/
  1521. /**
  1522. * This type represents touch interaction types in context of controls.
  1523. *
  1524. * @typedef {Object} ConstantsTouch
  1525. * @property {number} ROTATE - A rotate interaction.
  1526. * @property {number} PAN - A pan interaction.
  1527. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1528. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1529. **/
  1530. /**
  1531. * This type represents the different timestamp query types.
  1532. *
  1533. * @typedef {Object} ConstantsTimestampQuery
  1534. * @property {string} COMPUTE - A `compute` timestamp query.
  1535. * @property {string} RENDER - A `render` timestamp query.
  1536. **/
  1537. /**
  1538. * Represents the different interpolation sampling types.
  1539. *
  1540. * @typedef {Object} ConstantsInterpolationSamplingType
  1541. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1542. * @property {string} LINEAR - Linear interpolation.
  1543. * @property {string} FLAT - Flat interpolation.
  1544. */
  1545. /**
  1546. * Represents the different interpolation sampling modes.
  1547. *
  1548. * @typedef {Object} ConstantsInterpolationSamplingMode
  1549. * @property {string} NORMAL - Normal sampling mode.
  1550. * @property {string} CENTROID - Centroid sampling mode.
  1551. * @property {string} SAMPLE - Sample-specific sampling mode.
  1552. * @property {string} FIRST - Flat interpolation using the first vertex.
  1553. * @property {string} EITHER - Flat interpolation using either vertex.
  1554. */
  1555. /**
  1556. * Finds the minimum value in an array.
  1557. *
  1558. * @private
  1559. * @param {Array<number>} array - The array to search for the minimum value.
  1560. * @return {number} The minimum value in the array, or Infinity if the array is empty.
  1561. */
  1562. /**
  1563. * Checks if an array contains values that require Uint32 representation.
  1564. *
  1565. * This function determines whether the array contains any values >= 65535,
  1566. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1567. * The function iterates from the end of the array, assuming larger values are
  1568. * typically located at the end.
  1569. *
  1570. * @private
  1571. * @param {Array<number>} array - The array to check.
  1572. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1573. */
  1574. function arrayNeedsUint32( array ) {
  1575. // assumes larger values usually on last
  1576. for ( let i = array.length - 1; i >= 0; -- i ) {
  1577. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1578. }
  1579. return false;
  1580. }
  1581. /**
  1582. * Map of typed array constructor names to their constructors.
  1583. * This mapping enables dynamic creation of typed arrays based on string type names.
  1584. *
  1585. * @private
  1586. * @constant
  1587. * @type {Object<string, TypedArrayConstructor>}
  1588. */
  1589. const TYPED_ARRAYS = {
  1590. Int8Array: Int8Array,
  1591. Uint8Array: Uint8Array,
  1592. Uint8ClampedArray: Uint8ClampedArray,
  1593. Int16Array: Int16Array,
  1594. Uint16Array: Uint16Array,
  1595. Int32Array: Int32Array,
  1596. Uint32Array: Uint32Array,
  1597. Float32Array: Float32Array,
  1598. Float64Array: Float64Array
  1599. };
  1600. /**
  1601. * Creates a typed array of the specified type from the given buffer.
  1602. *
  1603. * @private
  1604. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1605. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1606. * @return {TypedArray} A new typed array of the specified type.
  1607. */
  1608. function getTypedArray( type, buffer ) {
  1609. return new TYPED_ARRAYS[ type ]( buffer );
  1610. }
  1611. /**
  1612. * Returns `true` if the given object is a typed array.
  1613. *
  1614. * @param {any} array - The object to check.
  1615. * @return {boolean} Whether the given object is a typed array.
  1616. */
  1617. function isTypedArray( array ) {
  1618. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1619. }
  1620. /**
  1621. * Creates an XHTML element with the specified tag name.
  1622. *
  1623. * This function uses the XHTML namespace to create DOM elements,
  1624. * ensuring proper element creation in XML-based contexts.
  1625. *
  1626. * @private
  1627. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1628. * @return {HTMLElement} The created XHTML element.
  1629. */
  1630. function createElementNS( name ) {
  1631. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1632. }
  1633. /**
  1634. * Creates a canvas element configured for block display.
  1635. *
  1636. * This is a convenience function that creates a canvas element with
  1637. * display style set to 'block', which is commonly used in three.js
  1638. * rendering contexts to avoid inline element spacing issues.
  1639. *
  1640. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1641. */
  1642. function createCanvasElement() {
  1643. const canvas = createElementNS( 'canvas' );
  1644. canvas.style.display = 'block';
  1645. return canvas;
  1646. }
  1647. /**
  1648. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1649. *
  1650. * @private
  1651. * @type {Object<string, boolean>}
  1652. */
  1653. const _cache = {};
  1654. /**
  1655. * Custom console function handler for intercepting log, warn, and error calls.
  1656. *
  1657. * @private
  1658. * @type {Function|null}
  1659. */
  1660. let _setConsoleFunction = null;
  1661. /**
  1662. * Sets a custom function to handle console output.
  1663. *
  1664. * This allows external code to intercept and handle console.log, console.warn,
  1665. * and console.error calls made by three.js, which is useful for custom logging,
  1666. * testing, or debugging workflows.
  1667. *
  1668. * @param {Function} fn - The function to handle console output. Should accept
  1669. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1670. */
  1671. function setConsoleFunction( fn ) {
  1672. _setConsoleFunction = fn;
  1673. }
  1674. /**
  1675. * Gets the currently set custom console function.
  1676. *
  1677. * @return {Function|null} The custom console function, or null if not set.
  1678. */
  1679. function getConsoleFunction() {
  1680. return _setConsoleFunction;
  1681. }
  1682. /**
  1683. * Logs an informational message with the 'THREE.' prefix.
  1684. *
  1685. * If a custom console function is set via setConsoleFunction(), it will be used
  1686. * instead of the native console.log. The first parameter is treated as the
  1687. * method name and is automatically prefixed with 'THREE.'.
  1688. *
  1689. * @param {...any} params - The message components. The first param is used as
  1690. * the method name and prefixed with 'THREE.'.
  1691. */
  1692. function log( ...params ) {
  1693. const message = 'THREE.' + params.shift();
  1694. if ( _setConsoleFunction ) {
  1695. _setConsoleFunction( 'log', message, ...params );
  1696. } else {
  1697. console.log( message, ...params );
  1698. }
  1699. }
  1700. /**
  1701. * Logs a warning message with the 'THREE.' prefix.
  1702. *
  1703. * If a custom console function is set via setConsoleFunction(), it will be used
  1704. * instead of the native console.warn. The first parameter is treated as the
  1705. * method name and is automatically prefixed with 'THREE.'.
  1706. *
  1707. * @param {...any} params - The message components. The first param is used as
  1708. * the method name and prefixed with 'THREE.'.
  1709. */
  1710. function warn( ...params ) {
  1711. const message = 'THREE.' + params.shift();
  1712. if ( _setConsoleFunction ) {
  1713. _setConsoleFunction( 'warn', message, ...params );
  1714. } else {
  1715. console.warn( message, ...params );
  1716. }
  1717. }
  1718. /**
  1719. * Logs an error message with the 'THREE.' prefix.
  1720. *
  1721. * If a custom console function is set via setConsoleFunction(), it will be used
  1722. * instead of the native console.error. The first parameter is treated as the
  1723. * method name and is automatically prefixed with 'THREE.'.
  1724. *
  1725. * @param {...any} params - The message components. The first param is used as
  1726. * the method name and prefixed with 'THREE.'.
  1727. */
  1728. function error( ...params ) {
  1729. const message = 'THREE.' + params.shift();
  1730. if ( _setConsoleFunction ) {
  1731. _setConsoleFunction( 'error', message, ...params );
  1732. } else {
  1733. console.error( message, ...params );
  1734. }
  1735. }
  1736. /**
  1737. * Logs a warning message only once, preventing duplicate warnings.
  1738. *
  1739. * This function maintains an internal cache of warning messages and will only
  1740. * output each unique warning message once. Useful for warnings that may be
  1741. * triggered repeatedly but should only be shown to the user once.
  1742. *
  1743. * @param {...any} params - The warning message components.
  1744. */
  1745. function warnOnce( ...params ) {
  1746. const message = params.join( ' ' );
  1747. if ( message in _cache ) return;
  1748. _cache[ message ] = true;
  1749. warn( ...params );
  1750. }
  1751. /**
  1752. * Asynchronously probes for WebGL sync object completion.
  1753. *
  1754. * This function creates a promise that resolves when the WebGL sync object
  1755. * signals completion or rejects if the sync operation fails. It uses polling
  1756. * at the specified interval to check the sync status without blocking the
  1757. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1758. *
  1759. * @private
  1760. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL rendering context.
  1761. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1762. * @param {number} interval - The polling interval in milliseconds.
  1763. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1764. */
  1765. function probeAsync( gl, sync, interval ) {
  1766. return new Promise( function ( resolve, reject ) {
  1767. function probe() {
  1768. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1769. case gl.WAIT_FAILED:
  1770. reject();
  1771. break;
  1772. case gl.TIMEOUT_EXPIRED:
  1773. setTimeout( probe, interval );
  1774. break;
  1775. default:
  1776. resolve();
  1777. }
  1778. }
  1779. setTimeout( probe, interval );
  1780. } );
  1781. }
  1782. /**
  1783. * This modules allows to dispatch event objects on custom JavaScript objects.
  1784. *
  1785. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1786. *
  1787. * Code Example:
  1788. * ```js
  1789. * class Car extends EventDispatcher {
  1790. * start() {
  1791. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1792. * }
  1793. *};
  1794. *
  1795. * // Using events with the custom object
  1796. * const car = new Car();
  1797. * car.addEventListener( 'start', function ( event ) {
  1798. * alert( event.message );
  1799. * } );
  1800. *
  1801. * car.start();
  1802. * ```
  1803. */
  1804. class EventDispatcher {
  1805. /**
  1806. * Adds the given event listener to the given event type.
  1807. *
  1808. * @param {string} type - The type of event to listen to.
  1809. * @param {Function} listener - The function that gets called when the event is fired.
  1810. */
  1811. addEventListener( type, listener ) {
  1812. if ( this._listeners === undefined ) this._listeners = {};
  1813. const listeners = this._listeners;
  1814. if ( listeners[ type ] === undefined ) {
  1815. listeners[ type ] = [];
  1816. }
  1817. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1818. listeners[ type ].push( listener );
  1819. }
  1820. }
  1821. /**
  1822. * Returns `true` if the given event listener has been added to the given event type.
  1823. *
  1824. * @param {string} type - The type of event.
  1825. * @param {Function} listener - The listener to check.
  1826. * @return {boolean} Whether the given event listener has been added to the given event type.
  1827. */
  1828. hasEventListener( type, listener ) {
  1829. const listeners = this._listeners;
  1830. if ( listeners === undefined ) return false;
  1831. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1832. }
  1833. /**
  1834. * Removes the given event listener from the given event type.
  1835. *
  1836. * @param {string} type - The type of event.
  1837. * @param {Function} listener - The listener to remove.
  1838. */
  1839. removeEventListener( type, listener ) {
  1840. const listeners = this._listeners;
  1841. if ( listeners === undefined ) return;
  1842. const listenerArray = listeners[ type ];
  1843. if ( listenerArray !== undefined ) {
  1844. const index = listenerArray.indexOf( listener );
  1845. if ( index !== -1 ) {
  1846. listenerArray.splice( index, 1 );
  1847. }
  1848. }
  1849. }
  1850. /**
  1851. * Dispatches an event object.
  1852. *
  1853. * @param {Object} event - The event that gets fired.
  1854. */
  1855. dispatchEvent( event ) {
  1856. const listeners = this._listeners;
  1857. if ( listeners === undefined ) return;
  1858. const listenerArray = listeners[ event.type ];
  1859. if ( listenerArray !== undefined ) {
  1860. event.target = this;
  1861. // Make a copy, in case listeners are removed while iterating.
  1862. const array = listenerArray.slice( 0 );
  1863. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1864. array[ i ].call( this, event );
  1865. }
  1866. event.target = null;
  1867. }
  1868. }
  1869. }
  1870. 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' ];
  1871. let _seed = 1234567;
  1872. const DEG2RAD = Math.PI / 180;
  1873. const RAD2DEG = 180 / Math.PI;
  1874. /**
  1875. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1876. * (universally unique identifier).
  1877. *
  1878. * @return {string} The UUID.
  1879. */
  1880. function generateUUID() {
  1881. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1882. const d0 = Math.random() * 0xffffffff | 0;
  1883. const d1 = Math.random() * 0xffffffff | 0;
  1884. const d2 = Math.random() * 0xffffffff | 0;
  1885. const d3 = Math.random() * 0xffffffff | 0;
  1886. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1887. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1888. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1889. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1890. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1891. return uuid.toLowerCase();
  1892. }
  1893. /**
  1894. * Clamps the given value between min and max.
  1895. *
  1896. * @param {number} value - The value to clamp.
  1897. * @param {number} min - The min value.
  1898. * @param {number} max - The max value.
  1899. * @return {number} The clamped value.
  1900. */
  1901. function clamp( value, min, max ) {
  1902. return Math.max( min, Math.min( max, value ) );
  1903. }
  1904. /**
  1905. * Computes the Euclidean modulo of the given parameters that
  1906. * is `( ( n % m ) + m ) % m`.
  1907. *
  1908. * @param {number} n - The first parameter.
  1909. * @param {number} m - The second parameter.
  1910. * @return {number} The Euclidean modulo.
  1911. */
  1912. function euclideanModulo( n, m ) {
  1913. // https://en.wikipedia.org/wiki/Modulo_operation
  1914. return ( ( n % m ) + m ) % m;
  1915. }
  1916. /**
  1917. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1918. * for the given value. `a2` must be greater than `a1`.
  1919. *
  1920. * @param {number} x - The value to be mapped.
  1921. * @param {number} a1 - Minimum value for range A.
  1922. * @param {number} a2 - Maximum value for range A.
  1923. * @param {number} b1 - Minimum value for range B.
  1924. * @param {number} b2 - Maximum value for range B.
  1925. * @return {number} The mapped value.
  1926. */
  1927. function mapLinear( x, a1, a2, b1, b2 ) {
  1928. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1929. }
  1930. /**
  1931. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1932. * between the start and end point.
  1933. *
  1934. * @param {number} x - The start point
  1935. * @param {number} y - The end point.
  1936. * @param {number} value - A value between start and end.
  1937. * @return {number} The interpolation factor.
  1938. */
  1939. function inverseLerp( x, y, value ) {
  1940. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1941. if ( x !== y ) {
  1942. return ( value - x ) / ( y - x );
  1943. } else {
  1944. return 0;
  1945. }
  1946. }
  1947. /**
  1948. * Returns a value linearly interpolated from two known points based on the given interval -
  1949. * `t = 0` will return `x` and `t = 1` will return `y`.
  1950. *
  1951. * @param {number} x - The start point
  1952. * @param {number} y - The end point.
  1953. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1954. * @return {number} The interpolated value.
  1955. */
  1956. function lerp( x, y, t ) {
  1957. return ( 1 - t ) * x + t * y;
  1958. }
  1959. /**
  1960. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1961. * time to maintain frame rate independent movement. For details, see
  1962. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1963. *
  1964. * @param {number} x - The current point.
  1965. * @param {number} y - The target point.
  1966. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1967. * and a lower value will make the movement more gradual.
  1968. * @param {number} dt - Delta time in seconds.
  1969. * @return {number} The interpolated value.
  1970. */
  1971. function damp( x, y, lambda, dt ) {
  1972. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1973. }
  1974. /**
  1975. * Returns a value that alternates between `0` and the given `length` parameter.
  1976. *
  1977. * @param {number} x - The value to pingpong.
  1978. * @param {number} [length=1] - The positive value the function will pingpong to.
  1979. * @return {number} The alternated value.
  1980. */
  1981. function pingpong( x, length = 1 ) {
  1982. // https://www.desmos.com/calculator/vcsjnyz7x4
  1983. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1984. }
  1985. /**
  1986. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1987. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1988. * the `min` and `max`.
  1989. *
  1990. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1991. *
  1992. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  1993. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  1994. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  1995. * @return {number} The alternated value.
  1996. */
  1997. function smoothstep( x, min, max ) {
  1998. if ( x <= min ) return 0;
  1999. if ( x >= max ) return 1;
  2000. x = ( x - min ) / ( max - min );
  2001. return x * x * ( 3 - 2 * x );
  2002. }
  2003. /**
  2004. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2005. * that has zero 1st and 2nd order derivatives at `x=0` and `x=1`.
  2006. *
  2007. * @param {number} x - The value to evaluate based on its position between `min` and `max`.
  2008. * @param {number} min - The min value. Any `x` value below `min` will be `0`. `min` must be lower than `max`.
  2009. * @param {number} max - The max value. Any `x` value above `max` will be `1`. `max` must be greater than `min`.
  2010. * @return {number} The alternated value.
  2011. */
  2012. function smootherstep( x, min, max ) {
  2013. if ( x <= min ) return 0;
  2014. if ( x >= max ) return 1;
  2015. x = ( x - min ) / ( max - min );
  2016. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2017. }
  2018. /**
  2019. * Returns a random integer from `<low, high>` interval.
  2020. *
  2021. * @param {number} low - The lower value boundary.
  2022. * @param {number} high - The upper value boundary
  2023. * @return {number} A random integer.
  2024. */
  2025. function randInt( low, high ) {
  2026. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2027. }
  2028. /**
  2029. * Returns a random float from `<low, high>` interval.
  2030. *
  2031. * @param {number} low - The lower value boundary.
  2032. * @param {number} high - The upper value boundary
  2033. * @return {number} A random float.
  2034. */
  2035. function randFloat( low, high ) {
  2036. return low + Math.random() * ( high - low );
  2037. }
  2038. /**
  2039. * Returns a random integer from `<-range/2, range/2>` interval.
  2040. *
  2041. * @param {number} range - Defines the value range.
  2042. * @return {number} A random float.
  2043. */
  2044. function randFloatSpread( range ) {
  2045. return range * ( 0.5 - Math.random() );
  2046. }
  2047. /**
  2048. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2049. *
  2050. * @param {number} [s] - The integer seed.
  2051. * @return {number} A random float.
  2052. */
  2053. function seededRandom( s ) {
  2054. if ( s !== undefined ) _seed = s;
  2055. // Mulberry32 generator
  2056. let t = _seed += 0x6D2B79F5;
  2057. t = Math.imul( t ^ t >>> 15, t | 1 );
  2058. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2059. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2060. }
  2061. /**
  2062. * Converts degrees to radians.
  2063. *
  2064. * @param {number} degrees - A value in degrees.
  2065. * @return {number} The converted value in radians.
  2066. */
  2067. function degToRad( degrees ) {
  2068. return degrees * DEG2RAD;
  2069. }
  2070. /**
  2071. * Converts radians to degrees.
  2072. *
  2073. * @param {number} radians - A value in radians.
  2074. * @return {number} The converted value in degrees.
  2075. */
  2076. function radToDeg( radians ) {
  2077. return radians * RAD2DEG;
  2078. }
  2079. /**
  2080. * Returns `true` if the given number is a power of two.
  2081. *
  2082. * @param {number} value - The value to check.
  2083. * @return {boolean} Whether the given number is a power of two or not.
  2084. */
  2085. function isPowerOfTwo( value ) {
  2086. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2087. }
  2088. /**
  2089. * Returns the smallest power of two that is greater than or equal to the given number.
  2090. *
  2091. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2092. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2093. */
  2094. function ceilPowerOfTwo( value ) {
  2095. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2096. }
  2097. /**
  2098. * Returns the largest power of two that is less than or equal to the given number.
  2099. *
  2100. * @param {number} value - The value to find a POT for. Must be greater than `0`.
  2101. * @return {number} The largest power of two that is less than or equal to the given number.
  2102. */
  2103. function floorPowerOfTwo( value ) {
  2104. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2105. }
  2106. /**
  2107. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2108. * defined by the given angles and order.
  2109. *
  2110. * Rotations are applied to the axes in the order specified by order:
  2111. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2112. *
  2113. * @param {Quaternion} q - The quaternion to set.
  2114. * @param {number} a - The rotation applied to the first axis, in radians.
  2115. * @param {number} b - The rotation applied to the second axis, in radians.
  2116. * @param {number} c - The rotation applied to the third axis, in radians.
  2117. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2118. */
  2119. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2120. const cos = Math.cos;
  2121. const sin = Math.sin;
  2122. const c2 = cos( b / 2 );
  2123. const s2 = sin( b / 2 );
  2124. const c13 = cos( ( a + c ) / 2 );
  2125. const s13 = sin( ( a + c ) / 2 );
  2126. const c1_3 = cos( ( a - c ) / 2 );
  2127. const s1_3 = sin( ( a - c ) / 2 );
  2128. const c3_1 = cos( ( c - a ) / 2 );
  2129. const s3_1 = sin( ( c - a ) / 2 );
  2130. switch ( order ) {
  2131. case 'XYX':
  2132. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2133. break;
  2134. case 'YZY':
  2135. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2136. break;
  2137. case 'ZXZ':
  2138. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2139. break;
  2140. case 'XZX':
  2141. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2142. break;
  2143. case 'YXY':
  2144. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2145. break;
  2146. case 'ZYZ':
  2147. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2148. break;
  2149. default:
  2150. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2151. }
  2152. }
  2153. /**
  2154. * Denormalizes the given value according to the given typed array.
  2155. *
  2156. * @param {number} value - The value to denormalize.
  2157. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2158. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2159. */
  2160. function denormalize( value, array ) {
  2161. switch ( array.constructor ) {
  2162. case Float32Array:
  2163. return value;
  2164. case Uint32Array:
  2165. return value / 4294967295.0;
  2166. case Uint16Array:
  2167. return value / 65535.0;
  2168. case Uint8Array:
  2169. return value / 255.0;
  2170. case Int32Array:
  2171. return Math.max( value / 2147483647.0, -1 );
  2172. case Int16Array:
  2173. return Math.max( value / 32767.0, -1 );
  2174. case Int8Array:
  2175. return Math.max( value / 127.0, -1 );
  2176. default:
  2177. throw new Error( 'Invalid component type.' );
  2178. }
  2179. }
  2180. /**
  2181. * Normalizes the given value according to the given typed array.
  2182. *
  2183. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2184. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2185. * @return {number} The normalize value.
  2186. */
  2187. function normalize( value, array ) {
  2188. switch ( array.constructor ) {
  2189. case Float32Array:
  2190. return value;
  2191. case Uint32Array:
  2192. return Math.round( value * 4294967295.0 );
  2193. case Uint16Array:
  2194. return Math.round( value * 65535.0 );
  2195. case Uint8Array:
  2196. return Math.round( value * 255.0 );
  2197. case Int32Array:
  2198. return Math.round( value * 2147483647.0 );
  2199. case Int16Array:
  2200. return Math.round( value * 32767.0 );
  2201. case Int8Array:
  2202. return Math.round( value * 127.0 );
  2203. default:
  2204. throw new Error( 'Invalid component type.' );
  2205. }
  2206. }
  2207. /**
  2208. * @class
  2209. * @classdesc A collection of math utility functions.
  2210. * @hideconstructor
  2211. */
  2212. const MathUtils = {
  2213. DEG2RAD: DEG2RAD,
  2214. RAD2DEG: RAD2DEG,
  2215. /**
  2216. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2217. * (universally unique identifier).
  2218. *
  2219. * @static
  2220. * @method
  2221. * @return {string} The UUID.
  2222. */
  2223. generateUUID: generateUUID,
  2224. /**
  2225. * Clamps the given value between min and max.
  2226. *
  2227. * @static
  2228. * @method
  2229. * @param {number} value - The value to clamp.
  2230. * @param {number} min - The min value.
  2231. * @param {number} max - The max value.
  2232. * @return {number} The clamped value.
  2233. */
  2234. clamp: clamp,
  2235. /**
  2236. * Computes the Euclidean modulo of the given parameters that
  2237. * is `( ( n % m ) + m ) % m`.
  2238. *
  2239. * @static
  2240. * @method
  2241. * @param {number} n - The first parameter.
  2242. * @param {number} m - The second parameter.
  2243. * @return {number} The Euclidean modulo.
  2244. */
  2245. euclideanModulo: euclideanModulo,
  2246. /**
  2247. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2248. * for the given value.
  2249. *
  2250. * @static
  2251. * @method
  2252. * @param {number} x - The value to be mapped.
  2253. * @param {number} a1 - Minimum value for range A.
  2254. * @param {number} a2 - Maximum value for range A.
  2255. * @param {number} b1 - Minimum value for range B.
  2256. * @param {number} b2 - Maximum value for range B.
  2257. * @return {number} The mapped value.
  2258. */
  2259. mapLinear: mapLinear,
  2260. /**
  2261. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2262. * between the start and end point.
  2263. *
  2264. * @static
  2265. * @method
  2266. * @param {number} x - The start point
  2267. * @param {number} y - The end point.
  2268. * @param {number} value - A value between start and end.
  2269. * @return {number} The interpolation factor.
  2270. */
  2271. inverseLerp: inverseLerp,
  2272. /**
  2273. * Returns a value linearly interpolated from two known points based on the given interval -
  2274. * `t = 0` will return `x` and `t = 1` will return `y`.
  2275. *
  2276. * @static
  2277. * @method
  2278. * @param {number} x - The start point
  2279. * @param {number} y - The end point.
  2280. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2281. * @return {number} The interpolated value.
  2282. */
  2283. lerp: lerp,
  2284. /**
  2285. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2286. * time to maintain frame rate independent movement. For details, see
  2287. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2288. *
  2289. * @static
  2290. * @method
  2291. * @param {number} x - The current point.
  2292. * @param {number} y - The target point.
  2293. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2294. * and a lower value will make the movement more gradual.
  2295. * @param {number} dt - Delta time in seconds.
  2296. * @return {number} The interpolated value.
  2297. */
  2298. damp: damp,
  2299. /**
  2300. * Returns a value that alternates between `0` and the given `length` parameter.
  2301. *
  2302. * @static
  2303. * @method
  2304. * @param {number} x - The value to pingpong.
  2305. * @param {number} [length=1] - The positive value the function will pingpong to.
  2306. * @return {number} The alternated value.
  2307. */
  2308. pingpong: pingpong,
  2309. /**
  2310. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2311. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2312. * the `min` and `max`.
  2313. *
  2314. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2315. *
  2316. * @static
  2317. * @method
  2318. * @param {number} x - The value to evaluate based on its position between min and max.
  2319. * @param {number} min - The min value. Any x value below min will be `0`.
  2320. * @param {number} max - The max value. Any x value above max will be `1`.
  2321. * @return {number} The alternated value.
  2322. */
  2323. smoothstep: smoothstep,
  2324. /**
  2325. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2326. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2327. *
  2328. * @static
  2329. * @method
  2330. * @param {number} x - The value to evaluate based on its position between min and max.
  2331. * @param {number} min - The min value. Any x value below min will be `0`.
  2332. * @param {number} max - The max value. Any x value above max will be `1`.
  2333. * @return {number} The alternated value.
  2334. */
  2335. smootherstep: smootherstep,
  2336. /**
  2337. * Returns a random integer from `<low, high>` interval.
  2338. *
  2339. * @static
  2340. * @method
  2341. * @param {number} low - The lower value boundary.
  2342. * @param {number} high - The upper value boundary
  2343. * @return {number} A random integer.
  2344. */
  2345. randInt: randInt,
  2346. /**
  2347. * Returns a random float from `<low, high>` interval.
  2348. *
  2349. * @static
  2350. * @method
  2351. * @param {number} low - The lower value boundary.
  2352. * @param {number} high - The upper value boundary
  2353. * @return {number} A random float.
  2354. */
  2355. randFloat: randFloat,
  2356. /**
  2357. * Returns a random integer from `<-range/2, range/2>` interval.
  2358. *
  2359. * @static
  2360. * @method
  2361. * @param {number} range - Defines the value range.
  2362. * @return {number} A random float.
  2363. */
  2364. randFloatSpread: randFloatSpread,
  2365. /**
  2366. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2367. *
  2368. * @static
  2369. * @method
  2370. * @param {number} [s] - The integer seed.
  2371. * @return {number} A random float.
  2372. */
  2373. seededRandom: seededRandom,
  2374. /**
  2375. * Converts degrees to radians.
  2376. *
  2377. * @static
  2378. * @method
  2379. * @param {number} degrees - A value in degrees.
  2380. * @return {number} The converted value in radians.
  2381. */
  2382. degToRad: degToRad,
  2383. /**
  2384. * Converts radians to degrees.
  2385. *
  2386. * @static
  2387. * @method
  2388. * @param {number} radians - A value in radians.
  2389. * @return {number} The converted value in degrees.
  2390. */
  2391. radToDeg: radToDeg,
  2392. /**
  2393. * Returns `true` if the given number is a power of two.
  2394. *
  2395. * @static
  2396. * @method
  2397. * @param {number} value - The value to check.
  2398. * @return {boolean} Whether the given number is a power of two or not.
  2399. */
  2400. isPowerOfTwo: isPowerOfTwo,
  2401. /**
  2402. * Returns the smallest power of two that is greater than or equal to the given number.
  2403. *
  2404. * @static
  2405. * @method
  2406. * @param {number} value - The value to find a POT for.
  2407. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2408. */
  2409. ceilPowerOfTwo: ceilPowerOfTwo,
  2410. /**
  2411. * Returns the largest power of two that is less than or equal to the given number.
  2412. *
  2413. * @static
  2414. * @method
  2415. * @param {number} value - The value to find a POT for.
  2416. * @return {number} The largest power of two that is less than or equal to the given number.
  2417. */
  2418. floorPowerOfTwo: floorPowerOfTwo,
  2419. /**
  2420. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2421. * defined by the given angles and order.
  2422. *
  2423. * Rotations are applied to the axes in the order specified by order:
  2424. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2425. *
  2426. * @static
  2427. * @method
  2428. * @param {Quaternion} q - The quaternion to set.
  2429. * @param {number} a - The rotation applied to the first axis, in radians.
  2430. * @param {number} b - The rotation applied to the second axis, in radians.
  2431. * @param {number} c - The rotation applied to the third axis, in radians.
  2432. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2433. */
  2434. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2435. /**
  2436. * Normalizes the given value according to the given typed array.
  2437. *
  2438. * @static
  2439. * @method
  2440. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2441. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2442. * @return {number} The normalize value.
  2443. */
  2444. normalize: normalize,
  2445. /**
  2446. * Denormalizes the given value according to the given typed array.
  2447. *
  2448. * @static
  2449. * @method
  2450. * @param {number} value - The value to denormalize.
  2451. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2452. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2453. */
  2454. denormalize: denormalize
  2455. };
  2456. /**
  2457. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2458. * (labeled x and y), which can be used to represent a number of things, such as:
  2459. *
  2460. * - A point in 2D space (i.e. a position on a plane).
  2461. * - A direction and length across a plane. In three.js the length will
  2462. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2463. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2464. * - Any arbitrary ordered pair of numbers.
  2465. *
  2466. * There are other things a 2D vector can be used to represent, such as
  2467. * momentum vectors, complex numbers and so on, however these are the most
  2468. * common uses in three.js.
  2469. *
  2470. * Iterating through a vector instance will yield its components `(x, y)` in
  2471. * the corresponding order.
  2472. * ```js
  2473. * const a = new THREE.Vector2( 0, 1 );
  2474. *
  2475. * //no arguments; will be initialised to (0, 0)
  2476. * const b = new THREE.Vector2( );
  2477. *
  2478. * const d = a.distanceTo( b );
  2479. * ```
  2480. */
  2481. class Vector2 {
  2482. /**
  2483. * Constructs a new 2D vector.
  2484. *
  2485. * @param {number} [x=0] - The x value of this vector.
  2486. * @param {number} [y=0] - The y value of this vector.
  2487. */
  2488. constructor( x = 0, y = 0 ) {
  2489. /**
  2490. * This flag can be used for type testing.
  2491. *
  2492. * @type {boolean}
  2493. * @readonly
  2494. * @default true
  2495. */
  2496. Vector2.prototype.isVector2 = true;
  2497. /**
  2498. * The x value of this vector.
  2499. *
  2500. * @type {number}
  2501. */
  2502. this.x = x;
  2503. /**
  2504. * The y value of this vector.
  2505. *
  2506. * @type {number}
  2507. */
  2508. this.y = y;
  2509. }
  2510. /**
  2511. * Alias for {@link Vector2#x}.
  2512. *
  2513. * @type {number}
  2514. */
  2515. get width() {
  2516. return this.x;
  2517. }
  2518. set width( value ) {
  2519. this.x = value;
  2520. }
  2521. /**
  2522. * Alias for {@link Vector2#y}.
  2523. *
  2524. * @type {number}
  2525. */
  2526. get height() {
  2527. return this.y;
  2528. }
  2529. set height( value ) {
  2530. this.y = value;
  2531. }
  2532. /**
  2533. * Sets the vector components.
  2534. *
  2535. * @param {number} x - The value of the x component.
  2536. * @param {number} y - The value of the y component.
  2537. * @return {Vector2} A reference to this vector.
  2538. */
  2539. set( x, y ) {
  2540. this.x = x;
  2541. this.y = y;
  2542. return this;
  2543. }
  2544. /**
  2545. * Sets the vector components to the same value.
  2546. *
  2547. * @param {number} scalar - The value to set for all vector components.
  2548. * @return {Vector2} A reference to this vector.
  2549. */
  2550. setScalar( scalar ) {
  2551. this.x = scalar;
  2552. this.y = scalar;
  2553. return this;
  2554. }
  2555. /**
  2556. * Sets the vector's x component to the given value
  2557. *
  2558. * @param {number} x - The value to set.
  2559. * @return {Vector2} A reference to this vector.
  2560. */
  2561. setX( x ) {
  2562. this.x = x;
  2563. return this;
  2564. }
  2565. /**
  2566. * Sets the vector's y component to the given value
  2567. *
  2568. * @param {number} y - The value to set.
  2569. * @return {Vector2} A reference to this vector.
  2570. */
  2571. setY( y ) {
  2572. this.y = y;
  2573. return this;
  2574. }
  2575. /**
  2576. * Allows to set a vector component with an index.
  2577. *
  2578. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2579. * @param {number} value - The value to set.
  2580. * @return {Vector2} A reference to this vector.
  2581. */
  2582. setComponent( index, value ) {
  2583. switch ( index ) {
  2584. case 0: this.x = value; break;
  2585. case 1: this.y = value; break;
  2586. default: throw new Error( 'index is out of range: ' + index );
  2587. }
  2588. return this;
  2589. }
  2590. /**
  2591. * Returns the value of the vector component which matches the given index.
  2592. *
  2593. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2594. * @return {number} A vector component value.
  2595. */
  2596. getComponent( index ) {
  2597. switch ( index ) {
  2598. case 0: return this.x;
  2599. case 1: return this.y;
  2600. default: throw new Error( 'index is out of range: ' + index );
  2601. }
  2602. }
  2603. /**
  2604. * Returns a new vector with copied values from this instance.
  2605. *
  2606. * @return {Vector2} A clone of this instance.
  2607. */
  2608. clone() {
  2609. return new this.constructor( this.x, this.y );
  2610. }
  2611. /**
  2612. * Copies the values of the given vector to this instance.
  2613. *
  2614. * @param {Vector2} v - The vector to copy.
  2615. * @return {Vector2} A reference to this vector.
  2616. */
  2617. copy( v ) {
  2618. this.x = v.x;
  2619. this.y = v.y;
  2620. return this;
  2621. }
  2622. /**
  2623. * Adds the given vector to this instance.
  2624. *
  2625. * @param {Vector2} v - The vector to add.
  2626. * @return {Vector2} A reference to this vector.
  2627. */
  2628. add( v ) {
  2629. this.x += v.x;
  2630. this.y += v.y;
  2631. return this;
  2632. }
  2633. /**
  2634. * Adds the given scalar value to all components of this instance.
  2635. *
  2636. * @param {number} s - The scalar to add.
  2637. * @return {Vector2} A reference to this vector.
  2638. */
  2639. addScalar( s ) {
  2640. this.x += s;
  2641. this.y += s;
  2642. return this;
  2643. }
  2644. /**
  2645. * Adds the given vectors and stores the result in this instance.
  2646. *
  2647. * @param {Vector2} a - The first vector.
  2648. * @param {Vector2} b - The second vector.
  2649. * @return {Vector2} A reference to this vector.
  2650. */
  2651. addVectors( a, b ) {
  2652. this.x = a.x + b.x;
  2653. this.y = a.y + b.y;
  2654. return this;
  2655. }
  2656. /**
  2657. * Adds the given vector scaled by the given factor to this instance.
  2658. *
  2659. * @param {Vector2} v - The vector.
  2660. * @param {number} s - The factor that scales `v`.
  2661. * @return {Vector2} A reference to this vector.
  2662. */
  2663. addScaledVector( v, s ) {
  2664. this.x += v.x * s;
  2665. this.y += v.y * s;
  2666. return this;
  2667. }
  2668. /**
  2669. * Subtracts the given vector from this instance.
  2670. *
  2671. * @param {Vector2} v - The vector to subtract.
  2672. * @return {Vector2} A reference to this vector.
  2673. */
  2674. sub( v ) {
  2675. this.x -= v.x;
  2676. this.y -= v.y;
  2677. return this;
  2678. }
  2679. /**
  2680. * Subtracts the given scalar value from all components of this instance.
  2681. *
  2682. * @param {number} s - The scalar to subtract.
  2683. * @return {Vector2} A reference to this vector.
  2684. */
  2685. subScalar( s ) {
  2686. this.x -= s;
  2687. this.y -= s;
  2688. return this;
  2689. }
  2690. /**
  2691. * Subtracts the given vectors and stores the result in this instance.
  2692. *
  2693. * @param {Vector2} a - The first vector.
  2694. * @param {Vector2} b - The second vector.
  2695. * @return {Vector2} A reference to this vector.
  2696. */
  2697. subVectors( a, b ) {
  2698. this.x = a.x - b.x;
  2699. this.y = a.y - b.y;
  2700. return this;
  2701. }
  2702. /**
  2703. * Multiplies the given vector with this instance.
  2704. *
  2705. * @param {Vector2} v - The vector to multiply.
  2706. * @return {Vector2} A reference to this vector.
  2707. */
  2708. multiply( v ) {
  2709. this.x *= v.x;
  2710. this.y *= v.y;
  2711. return this;
  2712. }
  2713. /**
  2714. * Multiplies the given scalar value with all components of this instance.
  2715. *
  2716. * @param {number} scalar - The scalar to multiply.
  2717. * @return {Vector2} A reference to this vector.
  2718. */
  2719. multiplyScalar( scalar ) {
  2720. this.x *= scalar;
  2721. this.y *= scalar;
  2722. return this;
  2723. }
  2724. /**
  2725. * Divides this instance by the given vector.
  2726. *
  2727. * @param {Vector2} v - The vector to divide.
  2728. * @return {Vector2} A reference to this vector.
  2729. */
  2730. divide( v ) {
  2731. this.x /= v.x;
  2732. this.y /= v.y;
  2733. return this;
  2734. }
  2735. /**
  2736. * Divides this vector by the given scalar.
  2737. *
  2738. * @param {number} scalar - The scalar to divide.
  2739. * @return {Vector2} A reference to this vector.
  2740. */
  2741. divideScalar( scalar ) {
  2742. return this.multiplyScalar( 1 / scalar );
  2743. }
  2744. /**
  2745. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2746. * the given 3x3 matrix.
  2747. *
  2748. * @param {Matrix3} m - The matrix to apply.
  2749. * @return {Vector2} A reference to this vector.
  2750. */
  2751. applyMatrix3( m ) {
  2752. const x = this.x, y = this.y;
  2753. const e = m.elements;
  2754. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2755. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2756. return this;
  2757. }
  2758. /**
  2759. * If this vector's x or y value is greater than the given vector's x or y
  2760. * value, replace that value with the corresponding min value.
  2761. *
  2762. * @param {Vector2} v - The vector.
  2763. * @return {Vector2} A reference to this vector.
  2764. */
  2765. min( v ) {
  2766. this.x = Math.min( this.x, v.x );
  2767. this.y = Math.min( this.y, v.y );
  2768. return this;
  2769. }
  2770. /**
  2771. * If this vector's x or y value is less than the given vector's x or y
  2772. * value, replace that value with the corresponding max value.
  2773. *
  2774. * @param {Vector2} v - The vector.
  2775. * @return {Vector2} A reference to this vector.
  2776. */
  2777. max( v ) {
  2778. this.x = Math.max( this.x, v.x );
  2779. this.y = Math.max( this.y, v.y );
  2780. return this;
  2781. }
  2782. /**
  2783. * If this vector's x or y value is greater than the max vector's x or y
  2784. * value, it is replaced by the corresponding value.
  2785. * If this vector's x or y value is less than the min vector's x or y value,
  2786. * it is replaced by the corresponding value.
  2787. *
  2788. * @param {Vector2} min - The minimum x and y values.
  2789. * @param {Vector2} max - The maximum x and y values in the desired range.
  2790. * @return {Vector2} A reference to this vector.
  2791. */
  2792. clamp( min, max ) {
  2793. // assumes min < max, componentwise
  2794. this.x = clamp( this.x, min.x, max.x );
  2795. this.y = clamp( this.y, min.y, max.y );
  2796. return this;
  2797. }
  2798. /**
  2799. * If this vector's x or y values are greater than the max value, they are
  2800. * replaced by the max value.
  2801. * If this vector's x or y values are less than the min value, they are
  2802. * replaced by the min value.
  2803. *
  2804. * @param {number} minVal - The minimum value the components will be clamped to.
  2805. * @param {number} maxVal - The maximum value the components will be clamped to.
  2806. * @return {Vector2} A reference to this vector.
  2807. */
  2808. clampScalar( minVal, maxVal ) {
  2809. this.x = clamp( this.x, minVal, maxVal );
  2810. this.y = clamp( this.y, minVal, maxVal );
  2811. return this;
  2812. }
  2813. /**
  2814. * If this vector's length is greater than the max value, it is replaced by
  2815. * the max value.
  2816. * If this vector's length is less than the min value, it is replaced by the
  2817. * min value.
  2818. *
  2819. * @param {number} min - The minimum value the vector length will be clamped to.
  2820. * @param {number} max - The maximum value the vector length will be clamped to.
  2821. * @return {Vector2} A reference to this vector.
  2822. */
  2823. clampLength( min, max ) {
  2824. const length = this.length();
  2825. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2826. }
  2827. /**
  2828. * The components of this vector are rounded down to the nearest integer value.
  2829. *
  2830. * @return {Vector2} A reference to this vector.
  2831. */
  2832. floor() {
  2833. this.x = Math.floor( this.x );
  2834. this.y = Math.floor( this.y );
  2835. return this;
  2836. }
  2837. /**
  2838. * The components of this vector are rounded up to the nearest integer value.
  2839. *
  2840. * @return {Vector2} A reference to this vector.
  2841. */
  2842. ceil() {
  2843. this.x = Math.ceil( this.x );
  2844. this.y = Math.ceil( this.y );
  2845. return this;
  2846. }
  2847. /**
  2848. * The components of this vector are rounded to the nearest integer value
  2849. *
  2850. * @return {Vector2} A reference to this vector.
  2851. */
  2852. round() {
  2853. this.x = Math.round( this.x );
  2854. this.y = Math.round( this.y );
  2855. return this;
  2856. }
  2857. /**
  2858. * The components of this vector are rounded towards zero (up if negative,
  2859. * down if positive) to an integer value.
  2860. *
  2861. * @return {Vector2} A reference to this vector.
  2862. */
  2863. roundToZero() {
  2864. this.x = Math.trunc( this.x );
  2865. this.y = Math.trunc( this.y );
  2866. return this;
  2867. }
  2868. /**
  2869. * Inverts this vector - i.e. sets x = -x and y = -y.
  2870. *
  2871. * @return {Vector2} A reference to this vector.
  2872. */
  2873. negate() {
  2874. this.x = - this.x;
  2875. this.y = - this.y;
  2876. return this;
  2877. }
  2878. /**
  2879. * Calculates the dot product of the given vector with this instance.
  2880. *
  2881. * @param {Vector2} v - The vector to compute the dot product with.
  2882. * @return {number} The result of the dot product.
  2883. */
  2884. dot( v ) {
  2885. return this.x * v.x + this.y * v.y;
  2886. }
  2887. /**
  2888. * Calculates the cross product of the given vector with this instance.
  2889. *
  2890. * @param {Vector2} v - The vector to compute the cross product with.
  2891. * @return {number} The result of the cross product.
  2892. */
  2893. cross( v ) {
  2894. return this.x * v.y - this.y * v.x;
  2895. }
  2896. /**
  2897. * Computes the square of the Euclidean length (straight-line length) from
  2898. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2899. * compare the length squared instead as it is slightly more efficient to calculate.
  2900. *
  2901. * @return {number} The square length of this vector.
  2902. */
  2903. lengthSq() {
  2904. return this.x * this.x + this.y * this.y;
  2905. }
  2906. /**
  2907. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2908. *
  2909. * @return {number} The length of this vector.
  2910. */
  2911. length() {
  2912. return Math.sqrt( this.x * this.x + this.y * this.y );
  2913. }
  2914. /**
  2915. * Computes the Manhattan length of this vector.
  2916. *
  2917. * @return {number} The length of this vector.
  2918. */
  2919. manhattanLength() {
  2920. return Math.abs( this.x ) + Math.abs( this.y );
  2921. }
  2922. /**
  2923. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2924. * with the same direction as this one, but with a vector length of `1`.
  2925. *
  2926. * @return {Vector2} A reference to this vector.
  2927. */
  2928. normalize() {
  2929. return this.divideScalar( this.length() || 1 );
  2930. }
  2931. /**
  2932. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2933. *
  2934. * @return {number} The angle in radians.
  2935. */
  2936. angle() {
  2937. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2938. return angle;
  2939. }
  2940. /**
  2941. * Returns the angle between the given vector and this instance in radians.
  2942. *
  2943. * @param {Vector2} v - The vector to compute the angle with.
  2944. * @return {number} The angle in radians.
  2945. */
  2946. angleTo( v ) {
  2947. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2948. if ( denominator === 0 ) return Math.PI / 2;
  2949. const theta = this.dot( v ) / denominator;
  2950. // clamp, to handle numerical problems
  2951. return Math.acos( clamp( theta, -1, 1 ) );
  2952. }
  2953. /**
  2954. * Computes the distance from the given vector to this instance.
  2955. *
  2956. * @param {Vector2} v - The vector to compute the distance to.
  2957. * @return {number} The distance.
  2958. */
  2959. distanceTo( v ) {
  2960. return Math.sqrt( this.distanceToSquared( v ) );
  2961. }
  2962. /**
  2963. * Computes the squared distance from the given vector to this instance.
  2964. * If you are just comparing the distance with another distance, you should compare
  2965. * the distance squared instead as it is slightly more efficient to calculate.
  2966. *
  2967. * @param {Vector2} v - The vector to compute the squared distance to.
  2968. * @return {number} The squared distance.
  2969. */
  2970. distanceToSquared( v ) {
  2971. const dx = this.x - v.x, dy = this.y - v.y;
  2972. return dx * dx + dy * dy;
  2973. }
  2974. /**
  2975. * Computes the Manhattan distance from the given vector to this instance.
  2976. *
  2977. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2978. * @return {number} The Manhattan distance.
  2979. */
  2980. manhattanDistanceTo( v ) {
  2981. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2982. }
  2983. /**
  2984. * Sets this vector to a vector with the same direction as this one, but
  2985. * with the specified length.
  2986. *
  2987. * @param {number} length - The new length of this vector.
  2988. * @return {Vector2} A reference to this vector.
  2989. */
  2990. setLength( length ) {
  2991. return this.normalize().multiplyScalar( length );
  2992. }
  2993. /**
  2994. * Linearly interpolates between the given vector and this instance, where
  2995. * alpha is the percent distance along the line - alpha = 0 will be this
  2996. * vector, and alpha = 1 will be the given one.
  2997. *
  2998. * @param {Vector2} v - The vector to interpolate towards.
  2999. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3000. * @return {Vector2} A reference to this vector.
  3001. */
  3002. lerp( v, alpha ) {
  3003. this.x += ( v.x - this.x ) * alpha;
  3004. this.y += ( v.y - this.y ) * alpha;
  3005. return this;
  3006. }
  3007. /**
  3008. * Linearly interpolates between the given vectors, where alpha is the percent
  3009. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3010. * be the second one. The result is stored in this instance.
  3011. *
  3012. * @param {Vector2} v1 - The first vector.
  3013. * @param {Vector2} v2 - The second vector.
  3014. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3015. * @return {Vector2} A reference to this vector.
  3016. */
  3017. lerpVectors( v1, v2, alpha ) {
  3018. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3019. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3020. return this;
  3021. }
  3022. /**
  3023. * Returns `true` if this vector is equal with the given one.
  3024. *
  3025. * @param {Vector2} v - The vector to test for equality.
  3026. * @return {boolean} Whether this vector is equal with the given one.
  3027. */
  3028. equals( v ) {
  3029. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3030. }
  3031. /**
  3032. * Sets this vector's x value to be `array[ offset ]` and y
  3033. * value to be `array[ offset + 1 ]`.
  3034. *
  3035. * @param {Array<number>} array - An array holding the vector component values.
  3036. * @param {number} [offset=0] - The offset into the array.
  3037. * @return {Vector2} A reference to this vector.
  3038. */
  3039. fromArray( array, offset = 0 ) {
  3040. this.x = array[ offset ];
  3041. this.y = array[ offset + 1 ];
  3042. return this;
  3043. }
  3044. /**
  3045. * Writes the components of this vector to the given array. If no array is provided,
  3046. * the method returns a new instance.
  3047. *
  3048. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3049. * @param {number} [offset=0] - Index of the first element in the array.
  3050. * @return {Array<number>} The vector components.
  3051. */
  3052. toArray( array = [], offset = 0 ) {
  3053. array[ offset ] = this.x;
  3054. array[ offset + 1 ] = this.y;
  3055. return array;
  3056. }
  3057. /**
  3058. * Sets the components of this vector from the given buffer attribute.
  3059. *
  3060. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3061. * @param {number} index - The index into the attribute.
  3062. * @return {Vector2} A reference to this vector.
  3063. */
  3064. fromBufferAttribute( attribute, index ) {
  3065. this.x = attribute.getX( index );
  3066. this.y = attribute.getY( index );
  3067. return this;
  3068. }
  3069. /**
  3070. * Rotates this vector around the given center by the given angle.
  3071. *
  3072. * @param {Vector2} center - The point around which to rotate.
  3073. * @param {number} angle - The angle to rotate, in radians.
  3074. * @return {Vector2} A reference to this vector.
  3075. */
  3076. rotateAround( center, angle ) {
  3077. const c = Math.cos( angle ), s = Math.sin( angle );
  3078. const x = this.x - center.x;
  3079. const y = this.y - center.y;
  3080. this.x = x * c - y * s + center.x;
  3081. this.y = x * s + y * c + center.y;
  3082. return this;
  3083. }
  3084. /**
  3085. * Sets each component of this vector to a pseudo-random value between `0` and
  3086. * `1`, excluding `1`.
  3087. *
  3088. * @return {Vector2} A reference to this vector.
  3089. */
  3090. random() {
  3091. this.x = Math.random();
  3092. this.y = Math.random();
  3093. return this;
  3094. }
  3095. *[ Symbol.iterator ]() {
  3096. yield this.x;
  3097. yield this.y;
  3098. }
  3099. }
  3100. /**
  3101. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3102. *
  3103. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3104. * the corresponding order.
  3105. *
  3106. * Note that three.js expects Quaternions to be normalized.
  3107. * ```js
  3108. * const quaternion = new THREE.Quaternion();
  3109. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3110. *
  3111. * const vector = new THREE.Vector3( 1, 0, 0 );
  3112. * vector.applyQuaternion( quaternion );
  3113. * ```
  3114. */
  3115. class Quaternion {
  3116. /**
  3117. * Constructs a new quaternion.
  3118. *
  3119. * @param {number} [x=0] - The x value of this quaternion.
  3120. * @param {number} [y=0] - The y value of this quaternion.
  3121. * @param {number} [z=0] - The z value of this quaternion.
  3122. * @param {number} [w=1] - The w value of this quaternion.
  3123. */
  3124. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3125. /**
  3126. * This flag can be used for type testing.
  3127. *
  3128. * @type {boolean}
  3129. * @readonly
  3130. * @default true
  3131. */
  3132. this.isQuaternion = true;
  3133. this._x = x;
  3134. this._y = y;
  3135. this._z = z;
  3136. this._w = w;
  3137. }
  3138. /**
  3139. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3140. * quaternion data are managed in flat arrays.
  3141. *
  3142. * @param {Array<number>} dst - The destination array.
  3143. * @param {number} dstOffset - An offset into the destination array.
  3144. * @param {Array<number>} src0 - The source array of the first quaternion.
  3145. * @param {number} srcOffset0 - An offset into the first source array.
  3146. * @param {Array<number>} src1 - The source array of the second quaternion.
  3147. * @param {number} srcOffset1 - An offset into the second source array.
  3148. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3149. * @see {@link Quaternion#slerp}
  3150. */
  3151. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3152. let x0 = src0[ srcOffset0 + 0 ],
  3153. y0 = src0[ srcOffset0 + 1 ],
  3154. z0 = src0[ srcOffset0 + 2 ],
  3155. w0 = src0[ srcOffset0 + 3 ];
  3156. let x1 = src1[ srcOffset1 + 0 ],
  3157. y1 = src1[ srcOffset1 + 1 ],
  3158. z1 = src1[ srcOffset1 + 2 ],
  3159. w1 = src1[ srcOffset1 + 3 ];
  3160. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3161. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3162. if ( dot < 0 ) {
  3163. x1 = - x1;
  3164. y1 = - y1;
  3165. z1 = - z1;
  3166. w1 = - w1;
  3167. dot = - dot;
  3168. }
  3169. let s = 1 - t;
  3170. if ( dot < 0.9995 ) {
  3171. // slerp
  3172. const theta = Math.acos( dot );
  3173. const sin = Math.sin( theta );
  3174. s = Math.sin( s * theta ) / sin;
  3175. t = Math.sin( t * theta ) / sin;
  3176. x0 = x0 * s + x1 * t;
  3177. y0 = y0 * s + y1 * t;
  3178. z0 = z0 * s + z1 * t;
  3179. w0 = w0 * s + w1 * t;
  3180. } else {
  3181. // for small angles, lerp then normalize
  3182. x0 = x0 * s + x1 * t;
  3183. y0 = y0 * s + y1 * t;
  3184. z0 = z0 * s + z1 * t;
  3185. w0 = w0 * s + w1 * t;
  3186. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3187. x0 *= f;
  3188. y0 *= f;
  3189. z0 *= f;
  3190. w0 *= f;
  3191. }
  3192. }
  3193. dst[ dstOffset ] = x0;
  3194. dst[ dstOffset + 1 ] = y0;
  3195. dst[ dstOffset + 2 ] = z0;
  3196. dst[ dstOffset + 3 ] = w0;
  3197. }
  3198. /**
  3199. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3200. * in flat arrays.
  3201. *
  3202. * @param {Array<number>} dst - The destination array.
  3203. * @param {number} dstOffset - An offset into the destination array.
  3204. * @param {Array<number>} src0 - The source array of the first quaternion.
  3205. * @param {number} srcOffset0 - An offset into the first source array.
  3206. * @param {Array<number>} src1 - The source array of the second quaternion.
  3207. * @param {number} srcOffset1 - An offset into the second source array.
  3208. * @return {Array<number>} The destination array.
  3209. * @see {@link Quaternion#multiplyQuaternions}.
  3210. */
  3211. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3212. const x0 = src0[ srcOffset0 ];
  3213. const y0 = src0[ srcOffset0 + 1 ];
  3214. const z0 = src0[ srcOffset0 + 2 ];
  3215. const w0 = src0[ srcOffset0 + 3 ];
  3216. const x1 = src1[ srcOffset1 ];
  3217. const y1 = src1[ srcOffset1 + 1 ];
  3218. const z1 = src1[ srcOffset1 + 2 ];
  3219. const w1 = src1[ srcOffset1 + 3 ];
  3220. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3221. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3222. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3223. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3224. return dst;
  3225. }
  3226. /**
  3227. * The x value of this quaternion.
  3228. *
  3229. * @type {number}
  3230. * @default 0
  3231. */
  3232. get x() {
  3233. return this._x;
  3234. }
  3235. set x( value ) {
  3236. this._x = value;
  3237. this._onChangeCallback();
  3238. }
  3239. /**
  3240. * The y value of this quaternion.
  3241. *
  3242. * @type {number}
  3243. * @default 0
  3244. */
  3245. get y() {
  3246. return this._y;
  3247. }
  3248. set y( value ) {
  3249. this._y = value;
  3250. this._onChangeCallback();
  3251. }
  3252. /**
  3253. * The z value of this quaternion.
  3254. *
  3255. * @type {number}
  3256. * @default 0
  3257. */
  3258. get z() {
  3259. return this._z;
  3260. }
  3261. set z( value ) {
  3262. this._z = value;
  3263. this._onChangeCallback();
  3264. }
  3265. /**
  3266. * The w value of this quaternion.
  3267. *
  3268. * @type {number}
  3269. * @default 1
  3270. */
  3271. get w() {
  3272. return this._w;
  3273. }
  3274. set w( value ) {
  3275. this._w = value;
  3276. this._onChangeCallback();
  3277. }
  3278. /**
  3279. * Sets the quaternion components.
  3280. *
  3281. * @param {number} x - The x value of this quaternion.
  3282. * @param {number} y - The y value of this quaternion.
  3283. * @param {number} z - The z value of this quaternion.
  3284. * @param {number} w - The w value of this quaternion.
  3285. * @return {Quaternion} A reference to this quaternion.
  3286. */
  3287. set( x, y, z, w ) {
  3288. this._x = x;
  3289. this._y = y;
  3290. this._z = z;
  3291. this._w = w;
  3292. this._onChangeCallback();
  3293. return this;
  3294. }
  3295. /**
  3296. * Returns a new quaternion with copied values from this instance.
  3297. *
  3298. * @return {Quaternion} A clone of this instance.
  3299. */
  3300. clone() {
  3301. return new this.constructor( this._x, this._y, this._z, this._w );
  3302. }
  3303. /**
  3304. * Copies the values of the given quaternion to this instance.
  3305. *
  3306. * @param {Quaternion} quaternion - The quaternion to copy.
  3307. * @return {Quaternion} A reference to this quaternion.
  3308. */
  3309. copy( quaternion ) {
  3310. this._x = quaternion.x;
  3311. this._y = quaternion.y;
  3312. this._z = quaternion.z;
  3313. this._w = quaternion.w;
  3314. this._onChangeCallback();
  3315. return this;
  3316. }
  3317. /**
  3318. * Sets this quaternion from the rotation specified by the given
  3319. * Euler angles.
  3320. *
  3321. * @param {Euler} euler - The Euler angles.
  3322. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3323. * @return {Quaternion} A reference to this quaternion.
  3324. */
  3325. setFromEuler( euler, update = true ) {
  3326. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3327. // http://www.mathworks.com/matlabcentral/fileexchange/
  3328. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3329. // content/SpinCalc.m
  3330. const cos = Math.cos;
  3331. const sin = Math.sin;
  3332. const c1 = cos( x / 2 );
  3333. const c2 = cos( y / 2 );
  3334. const c3 = cos( z / 2 );
  3335. const s1 = sin( x / 2 );
  3336. const s2 = sin( y / 2 );
  3337. const s3 = sin( z / 2 );
  3338. switch ( order ) {
  3339. case 'XYZ':
  3340. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3341. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3342. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3343. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3344. break;
  3345. case 'YXZ':
  3346. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3347. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3348. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3349. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3350. break;
  3351. case 'ZXY':
  3352. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3353. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3354. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3355. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3356. break;
  3357. case 'ZYX':
  3358. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3359. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3360. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3361. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3362. break;
  3363. case 'YZX':
  3364. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3365. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3366. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3367. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3368. break;
  3369. case 'XZY':
  3370. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3371. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3372. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3373. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3374. break;
  3375. default:
  3376. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3377. }
  3378. if ( update === true ) this._onChangeCallback();
  3379. return this;
  3380. }
  3381. /**
  3382. * Sets this quaternion from the given axis and angle.
  3383. *
  3384. * @param {Vector3} axis - The normalized axis.
  3385. * @param {number} angle - The angle in radians.
  3386. * @return {Quaternion} A reference to this quaternion.
  3387. */
  3388. setFromAxisAngle( axis, angle ) {
  3389. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3390. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3391. this._x = axis.x * s;
  3392. this._y = axis.y * s;
  3393. this._z = axis.z * s;
  3394. this._w = Math.cos( halfAngle );
  3395. this._onChangeCallback();
  3396. return this;
  3397. }
  3398. /**
  3399. * Sets this quaternion from the given rotation matrix.
  3400. *
  3401. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3402. * @return {Quaternion} A reference to this quaternion.
  3403. */
  3404. setFromRotationMatrix( m ) {
  3405. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3406. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3407. const te = m.elements,
  3408. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3409. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3410. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3411. trace = m11 + m22 + m33;
  3412. if ( trace > 0 ) {
  3413. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3414. this._w = 0.25 / s;
  3415. this._x = ( m32 - m23 ) * s;
  3416. this._y = ( m13 - m31 ) * s;
  3417. this._z = ( m21 - m12 ) * s;
  3418. } else if ( m11 > m22 && m11 > m33 ) {
  3419. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3420. this._w = ( m32 - m23 ) / s;
  3421. this._x = 0.25 * s;
  3422. this._y = ( m12 + m21 ) / s;
  3423. this._z = ( m13 + m31 ) / s;
  3424. } else if ( m22 > m33 ) {
  3425. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3426. this._w = ( m13 - m31 ) / s;
  3427. this._x = ( m12 + m21 ) / s;
  3428. this._y = 0.25 * s;
  3429. this._z = ( m23 + m32 ) / s;
  3430. } else {
  3431. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3432. this._w = ( m21 - m12 ) / s;
  3433. this._x = ( m13 + m31 ) / s;
  3434. this._y = ( m23 + m32 ) / s;
  3435. this._z = 0.25 * s;
  3436. }
  3437. this._onChangeCallback();
  3438. return this;
  3439. }
  3440. /**
  3441. * Sets this quaternion to the rotation required to rotate the direction vector
  3442. * `vFrom` to the direction vector `vTo`.
  3443. *
  3444. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3445. * @param {Vector3} vTo - The second (normalized) direction vector.
  3446. * @return {Quaternion} A reference to this quaternion.
  3447. */
  3448. setFromUnitVectors( vFrom, vTo ) {
  3449. // assumes direction vectors vFrom and vTo are normalized
  3450. let r = vFrom.dot( vTo ) + 1;
  3451. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3452. // vFrom and vTo point in opposite directions
  3453. r = 0;
  3454. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3455. this._x = - vFrom.y;
  3456. this._y = vFrom.x;
  3457. this._z = 0;
  3458. this._w = r;
  3459. } else {
  3460. this._x = 0;
  3461. this._y = - vFrom.z;
  3462. this._z = vFrom.y;
  3463. this._w = r;
  3464. }
  3465. } else {
  3466. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3467. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3468. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3469. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3470. this._w = r;
  3471. }
  3472. return this.normalize();
  3473. }
  3474. /**
  3475. * Returns the angle between this quaternion and the given one in radians.
  3476. *
  3477. * @param {Quaternion} q - The quaternion to compute the angle with.
  3478. * @return {number} The angle in radians.
  3479. */
  3480. angleTo( q ) {
  3481. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3482. }
  3483. /**
  3484. * Rotates this quaternion by a given angular step to the given quaternion.
  3485. * The method ensures that the final quaternion will not overshoot `q`.
  3486. *
  3487. * @param {Quaternion} q - The target quaternion.
  3488. * @param {number} step - The angular step in radians.
  3489. * @return {Quaternion} A reference to this quaternion.
  3490. */
  3491. rotateTowards( q, step ) {
  3492. const angle = this.angleTo( q );
  3493. if ( angle === 0 ) return this;
  3494. const t = Math.min( 1, step / angle );
  3495. this.slerp( q, t );
  3496. return this;
  3497. }
  3498. /**
  3499. * Sets this quaternion to the identity quaternion; that is, to the
  3500. * quaternion that represents "no rotation".
  3501. *
  3502. * @return {Quaternion} A reference to this quaternion.
  3503. */
  3504. identity() {
  3505. return this.set( 0, 0, 0, 1 );
  3506. }
  3507. /**
  3508. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3509. * quaternion is assumed to have unit length.
  3510. *
  3511. * @return {Quaternion} A reference to this quaternion.
  3512. */
  3513. invert() {
  3514. return this.conjugate();
  3515. }
  3516. /**
  3517. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3518. * quaternion represents the same rotation in the opposite direction about
  3519. * the rotational axis.
  3520. *
  3521. * @return {Quaternion} A reference to this quaternion.
  3522. */
  3523. conjugate() {
  3524. this._x *= -1;
  3525. this._y *= -1;
  3526. this._z *= -1;
  3527. this._onChangeCallback();
  3528. return this;
  3529. }
  3530. /**
  3531. * Calculates the dot product of this quaternion and the given one.
  3532. *
  3533. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3534. * @return {number} The result of the dot product.
  3535. */
  3536. dot( v ) {
  3537. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3538. }
  3539. /**
  3540. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3541. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3542. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3543. * {@link Quaternion#length}.
  3544. *
  3545. * @return {number} The squared Euclidean length.
  3546. */
  3547. lengthSq() {
  3548. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3549. }
  3550. /**
  3551. * Computes the Euclidean length (straight-line length) of this quaternion,
  3552. * considered as a 4 dimensional vector.
  3553. *
  3554. * @return {number} The Euclidean length.
  3555. */
  3556. length() {
  3557. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3558. }
  3559. /**
  3560. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3561. * the same rotation as this one, but has a length equal to `1`.
  3562. *
  3563. * @return {Quaternion} A reference to this quaternion.
  3564. */
  3565. normalize() {
  3566. let l = this.length();
  3567. if ( l === 0 ) {
  3568. this._x = 0;
  3569. this._y = 0;
  3570. this._z = 0;
  3571. this._w = 1;
  3572. } else {
  3573. l = 1 / l;
  3574. this._x = this._x * l;
  3575. this._y = this._y * l;
  3576. this._z = this._z * l;
  3577. this._w = this._w * l;
  3578. }
  3579. this._onChangeCallback();
  3580. return this;
  3581. }
  3582. /**
  3583. * Multiplies this quaternion by the given one.
  3584. *
  3585. * @param {Quaternion} q - The quaternion.
  3586. * @return {Quaternion} A reference to this quaternion.
  3587. */
  3588. multiply( q ) {
  3589. return this.multiplyQuaternions( this, q );
  3590. }
  3591. /**
  3592. * Pre-multiplies this quaternion by the given one.
  3593. *
  3594. * @param {Quaternion} q - The quaternion.
  3595. * @return {Quaternion} A reference to this quaternion.
  3596. */
  3597. premultiply( q ) {
  3598. return this.multiplyQuaternions( q, this );
  3599. }
  3600. /**
  3601. * Multiplies the given quaternions and stores the result in this instance.
  3602. *
  3603. * @param {Quaternion} a - The first quaternion.
  3604. * @param {Quaternion} b - The second quaternion.
  3605. * @return {Quaternion} A reference to this quaternion.
  3606. */
  3607. multiplyQuaternions( a, b ) {
  3608. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3609. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3610. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3611. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3612. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3613. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3614. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3615. this._onChangeCallback();
  3616. return this;
  3617. }
  3618. /**
  3619. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3620. *
  3621. * @param {Quaternion} qb - The target quaternion.
  3622. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3623. * @return {Quaternion} A reference to this quaternion.
  3624. */
  3625. slerp( qb, t ) {
  3626. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3627. let dot = this.dot( qb );
  3628. if ( dot < 0 ) {
  3629. x = - x;
  3630. y = - y;
  3631. z = - z;
  3632. w = - w;
  3633. dot = - dot;
  3634. }
  3635. let s = 1 - t;
  3636. if ( dot < 0.9995 ) {
  3637. // slerp
  3638. const theta = Math.acos( dot );
  3639. const sin = Math.sin( theta );
  3640. s = Math.sin( s * theta ) / sin;
  3641. t = Math.sin( t * theta ) / sin;
  3642. this._x = this._x * s + x * t;
  3643. this._y = this._y * s + y * t;
  3644. this._z = this._z * s + z * t;
  3645. this._w = this._w * s + w * t;
  3646. this._onChangeCallback();
  3647. } else {
  3648. // for small angles, lerp then normalize
  3649. this._x = this._x * s + x * t;
  3650. this._y = this._y * s + y * t;
  3651. this._z = this._z * s + z * t;
  3652. this._w = this._w * s + w * t;
  3653. this.normalize(); // normalize calls _onChangeCallback()
  3654. }
  3655. return this;
  3656. }
  3657. /**
  3658. * Performs a spherical linear interpolation between the given quaternions
  3659. * and stores the result in this quaternion.
  3660. *
  3661. * @param {Quaternion} qa - The source quaternion.
  3662. * @param {Quaternion} qb - The target quaternion.
  3663. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3664. * @return {Quaternion} A reference to this quaternion.
  3665. */
  3666. slerpQuaternions( qa, qb, t ) {
  3667. return this.copy( qa ).slerp( qb, t );
  3668. }
  3669. /**
  3670. * Sets this quaternion to a uniformly random, normalized quaternion.
  3671. *
  3672. * @return {Quaternion} A reference to this quaternion.
  3673. */
  3674. random() {
  3675. // Ken Shoemake
  3676. // Uniform random rotations
  3677. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3678. const theta1 = 2 * Math.PI * Math.random();
  3679. const theta2 = 2 * Math.PI * Math.random();
  3680. const x0 = Math.random();
  3681. const r1 = Math.sqrt( 1 - x0 );
  3682. const r2 = Math.sqrt( x0 );
  3683. return this.set(
  3684. r1 * Math.sin( theta1 ),
  3685. r1 * Math.cos( theta1 ),
  3686. r2 * Math.sin( theta2 ),
  3687. r2 * Math.cos( theta2 ),
  3688. );
  3689. }
  3690. /**
  3691. * Returns `true` if this quaternion is equal with the given one.
  3692. *
  3693. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3694. * @return {boolean} Whether this quaternion is equal with the given one.
  3695. */
  3696. equals( quaternion ) {
  3697. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3698. }
  3699. /**
  3700. * Sets this quaternion's components from the given array.
  3701. *
  3702. * @param {Array<number>} array - An array holding the quaternion component values.
  3703. * @param {number} [offset=0] - The offset into the array.
  3704. * @return {Quaternion} A reference to this quaternion.
  3705. */
  3706. fromArray( array, offset = 0 ) {
  3707. this._x = array[ offset ];
  3708. this._y = array[ offset + 1 ];
  3709. this._z = array[ offset + 2 ];
  3710. this._w = array[ offset + 3 ];
  3711. this._onChangeCallback();
  3712. return this;
  3713. }
  3714. /**
  3715. * Writes the components of this quaternion to the given array. If no array is provided,
  3716. * the method returns a new instance.
  3717. *
  3718. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3719. * @param {number} [offset=0] - Index of the first element in the array.
  3720. * @return {Array<number>} The quaternion components.
  3721. */
  3722. toArray( array = [], offset = 0 ) {
  3723. array[ offset ] = this._x;
  3724. array[ offset + 1 ] = this._y;
  3725. array[ offset + 2 ] = this._z;
  3726. array[ offset + 3 ] = this._w;
  3727. return array;
  3728. }
  3729. /**
  3730. * Sets the components of this quaternion from the given buffer attribute.
  3731. *
  3732. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3733. * @param {number} index - The index into the attribute.
  3734. * @return {Quaternion} A reference to this quaternion.
  3735. */
  3736. fromBufferAttribute( attribute, index ) {
  3737. this._x = attribute.getX( index );
  3738. this._y = attribute.getY( index );
  3739. this._z = attribute.getZ( index );
  3740. this._w = attribute.getW( index );
  3741. this._onChangeCallback();
  3742. return this;
  3743. }
  3744. /**
  3745. * This methods defines the serialization result of this class. Returns the
  3746. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3747. *
  3748. * @return {Array<number>} The serialized quaternion.
  3749. */
  3750. toJSON() {
  3751. return this.toArray();
  3752. }
  3753. _onChange( callback ) {
  3754. this._onChangeCallback = callback;
  3755. return this;
  3756. }
  3757. _onChangeCallback() {}
  3758. *[ Symbol.iterator ]() {
  3759. yield this._x;
  3760. yield this._y;
  3761. yield this._z;
  3762. yield this._w;
  3763. }
  3764. }
  3765. /**
  3766. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3767. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3768. *
  3769. * - A point in 3D space.
  3770. * - A direction and length in 3D space. In three.js the length will
  3771. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3772. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3773. * - Any arbitrary ordered triplet of numbers.
  3774. *
  3775. * There are other things a 3D vector can be used to represent, such as
  3776. * momentum vectors and so on, however these are the most
  3777. * common uses in three.js.
  3778. *
  3779. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3780. * the corresponding order.
  3781. * ```js
  3782. * const a = new THREE.Vector3( 0, 1, 0 );
  3783. *
  3784. * //no arguments; will be initialised to (0, 0, 0)
  3785. * const b = new THREE.Vector3( );
  3786. *
  3787. * const d = a.distanceTo( b );
  3788. * ```
  3789. */
  3790. class Vector3 {
  3791. /**
  3792. * Constructs a new 3D vector.
  3793. *
  3794. * @param {number} [x=0] - The x value of this vector.
  3795. * @param {number} [y=0] - The y value of this vector.
  3796. * @param {number} [z=0] - The z value of this vector.
  3797. */
  3798. constructor( x = 0, y = 0, z = 0 ) {
  3799. /**
  3800. * This flag can be used for type testing.
  3801. *
  3802. * @type {boolean}
  3803. * @readonly
  3804. * @default true
  3805. */
  3806. Vector3.prototype.isVector3 = true;
  3807. /**
  3808. * The x value of this vector.
  3809. *
  3810. * @type {number}
  3811. */
  3812. this.x = x;
  3813. /**
  3814. * The y value of this vector.
  3815. *
  3816. * @type {number}
  3817. */
  3818. this.y = y;
  3819. /**
  3820. * The z value of this vector.
  3821. *
  3822. * @type {number}
  3823. */
  3824. this.z = z;
  3825. }
  3826. /**
  3827. * Sets the vector components.
  3828. *
  3829. * @param {number} x - The value of the x component.
  3830. * @param {number} y - The value of the y component.
  3831. * @param {number} z - The value of the z component.
  3832. * @return {Vector3} A reference to this vector.
  3833. */
  3834. set( x, y, z ) {
  3835. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3836. this.x = x;
  3837. this.y = y;
  3838. this.z = z;
  3839. return this;
  3840. }
  3841. /**
  3842. * Sets the vector components to the same value.
  3843. *
  3844. * @param {number} scalar - The value to set for all vector components.
  3845. * @return {Vector3} A reference to this vector.
  3846. */
  3847. setScalar( scalar ) {
  3848. this.x = scalar;
  3849. this.y = scalar;
  3850. this.z = scalar;
  3851. return this;
  3852. }
  3853. /**
  3854. * Sets the vector's x component to the given value.
  3855. *
  3856. * @param {number} x - The value to set.
  3857. * @return {Vector3} A reference to this vector.
  3858. */
  3859. setX( x ) {
  3860. this.x = x;
  3861. return this;
  3862. }
  3863. /**
  3864. * Sets the vector's y component to the given value.
  3865. *
  3866. * @param {number} y - The value to set.
  3867. * @return {Vector3} A reference to this vector.
  3868. */
  3869. setY( y ) {
  3870. this.y = y;
  3871. return this;
  3872. }
  3873. /**
  3874. * Sets the vector's z component to the given value.
  3875. *
  3876. * @param {number} z - The value to set.
  3877. * @return {Vector3} A reference to this vector.
  3878. */
  3879. setZ( z ) {
  3880. this.z = z;
  3881. return this;
  3882. }
  3883. /**
  3884. * Allows to set a vector component with an index.
  3885. *
  3886. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3887. * @param {number} value - The value to set.
  3888. * @return {Vector3} A reference to this vector.
  3889. */
  3890. setComponent( index, value ) {
  3891. switch ( index ) {
  3892. case 0: this.x = value; break;
  3893. case 1: this.y = value; break;
  3894. case 2: this.z = value; break;
  3895. default: throw new Error( 'index is out of range: ' + index );
  3896. }
  3897. return this;
  3898. }
  3899. /**
  3900. * Returns the value of the vector component which matches the given index.
  3901. *
  3902. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3903. * @return {number} A vector component value.
  3904. */
  3905. getComponent( index ) {
  3906. switch ( index ) {
  3907. case 0: return this.x;
  3908. case 1: return this.y;
  3909. case 2: return this.z;
  3910. default: throw new Error( 'index is out of range: ' + index );
  3911. }
  3912. }
  3913. /**
  3914. * Returns a new vector with copied values from this instance.
  3915. *
  3916. * @return {Vector3} A clone of this instance.
  3917. */
  3918. clone() {
  3919. return new this.constructor( this.x, this.y, this.z );
  3920. }
  3921. /**
  3922. * Copies the values of the given vector to this instance.
  3923. *
  3924. * @param {Vector3} v - The vector to copy.
  3925. * @return {Vector3} A reference to this vector.
  3926. */
  3927. copy( v ) {
  3928. this.x = v.x;
  3929. this.y = v.y;
  3930. this.z = v.z;
  3931. return this;
  3932. }
  3933. /**
  3934. * Adds the given vector to this instance.
  3935. *
  3936. * @param {Vector3} v - The vector to add.
  3937. * @return {Vector3} A reference to this vector.
  3938. */
  3939. add( v ) {
  3940. this.x += v.x;
  3941. this.y += v.y;
  3942. this.z += v.z;
  3943. return this;
  3944. }
  3945. /**
  3946. * Adds the given scalar value to all components of this instance.
  3947. *
  3948. * @param {number} s - The scalar to add.
  3949. * @return {Vector3} A reference to this vector.
  3950. */
  3951. addScalar( s ) {
  3952. this.x += s;
  3953. this.y += s;
  3954. this.z += s;
  3955. return this;
  3956. }
  3957. /**
  3958. * Adds the given vectors and stores the result in this instance.
  3959. *
  3960. * @param {Vector3} a - The first vector.
  3961. * @param {Vector3} b - The second vector.
  3962. * @return {Vector3} A reference to this vector.
  3963. */
  3964. addVectors( a, b ) {
  3965. this.x = a.x + b.x;
  3966. this.y = a.y + b.y;
  3967. this.z = a.z + b.z;
  3968. return this;
  3969. }
  3970. /**
  3971. * Adds the given vector scaled by the given factor to this instance.
  3972. *
  3973. * @param {Vector3|Vector4} v - The vector.
  3974. * @param {number} s - The factor that scales `v`.
  3975. * @return {Vector3} A reference to this vector.
  3976. */
  3977. addScaledVector( v, s ) {
  3978. this.x += v.x * s;
  3979. this.y += v.y * s;
  3980. this.z += v.z * s;
  3981. return this;
  3982. }
  3983. /**
  3984. * Subtracts the given vector from this instance.
  3985. *
  3986. * @param {Vector3} v - The vector to subtract.
  3987. * @return {Vector3} A reference to this vector.
  3988. */
  3989. sub( v ) {
  3990. this.x -= v.x;
  3991. this.y -= v.y;
  3992. this.z -= v.z;
  3993. return this;
  3994. }
  3995. /**
  3996. * Subtracts the given scalar value from all components of this instance.
  3997. *
  3998. * @param {number} s - The scalar to subtract.
  3999. * @return {Vector3} A reference to this vector.
  4000. */
  4001. subScalar( s ) {
  4002. this.x -= s;
  4003. this.y -= s;
  4004. this.z -= s;
  4005. return this;
  4006. }
  4007. /**
  4008. * Subtracts the given vectors and stores the result in this instance.
  4009. *
  4010. * @param {Vector3} a - The first vector.
  4011. * @param {Vector3} b - The second vector.
  4012. * @return {Vector3} A reference to this vector.
  4013. */
  4014. subVectors( a, b ) {
  4015. this.x = a.x - b.x;
  4016. this.y = a.y - b.y;
  4017. this.z = a.z - b.z;
  4018. return this;
  4019. }
  4020. /**
  4021. * Multiplies the given vector with this instance.
  4022. *
  4023. * @param {Vector3} v - The vector to multiply.
  4024. * @return {Vector3} A reference to this vector.
  4025. */
  4026. multiply( v ) {
  4027. this.x *= v.x;
  4028. this.y *= v.y;
  4029. this.z *= v.z;
  4030. return this;
  4031. }
  4032. /**
  4033. * Multiplies the given scalar value with all components of this instance.
  4034. *
  4035. * @param {number} scalar - The scalar to multiply.
  4036. * @return {Vector3} A reference to this vector.
  4037. */
  4038. multiplyScalar( scalar ) {
  4039. this.x *= scalar;
  4040. this.y *= scalar;
  4041. this.z *= scalar;
  4042. return this;
  4043. }
  4044. /**
  4045. * Multiplies the given vectors and stores the result in this instance.
  4046. *
  4047. * @param {Vector3} a - The first vector.
  4048. * @param {Vector3} b - The second vector.
  4049. * @return {Vector3} A reference to this vector.
  4050. */
  4051. multiplyVectors( a, b ) {
  4052. this.x = a.x * b.x;
  4053. this.y = a.y * b.y;
  4054. this.z = a.z * b.z;
  4055. return this;
  4056. }
  4057. /**
  4058. * Applies the given Euler rotation to this vector.
  4059. *
  4060. * @param {Euler} euler - The Euler angles.
  4061. * @return {Vector3} A reference to this vector.
  4062. */
  4063. applyEuler( euler ) {
  4064. return this.applyQuaternion( _quaternion$5.setFromEuler( euler ) );
  4065. }
  4066. /**
  4067. * Applies a rotation specified by an axis and an angle to this vector.
  4068. *
  4069. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4070. * @param {number} angle - The angle in radians.
  4071. * @return {Vector3} A reference to this vector.
  4072. */
  4073. applyAxisAngle( axis, angle ) {
  4074. return this.applyQuaternion( _quaternion$5.setFromAxisAngle( axis, angle ) );
  4075. }
  4076. /**
  4077. * Multiplies this vector with the given 3x3 matrix.
  4078. *
  4079. * @param {Matrix3} m - The 3x3 matrix.
  4080. * @return {Vector3} A reference to this vector.
  4081. */
  4082. applyMatrix3( m ) {
  4083. const x = this.x, y = this.y, z = this.z;
  4084. const e = m.elements;
  4085. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4086. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4087. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4088. return this;
  4089. }
  4090. /**
  4091. * Multiplies this vector by the given normal matrix and normalizes
  4092. * the result.
  4093. *
  4094. * @param {Matrix3} m - The normal matrix.
  4095. * @return {Vector3} A reference to this vector.
  4096. */
  4097. applyNormalMatrix( m ) {
  4098. return this.applyMatrix3( m ).normalize();
  4099. }
  4100. /**
  4101. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4102. * divides by perspective.
  4103. *
  4104. * @param {Matrix4} m - The matrix to apply.
  4105. * @return {Vector3} A reference to this vector.
  4106. */
  4107. applyMatrix4( m ) {
  4108. const x = this.x, y = this.y, z = this.z;
  4109. const e = m.elements;
  4110. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4111. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4112. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4113. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4114. return this;
  4115. }
  4116. /**
  4117. * Applies the given Quaternion to this vector.
  4118. *
  4119. * @param {Quaternion} q - The Quaternion.
  4120. * @return {Vector3} A reference to this vector.
  4121. */
  4122. applyQuaternion( q ) {
  4123. // quaternion q is assumed to have unit length
  4124. const vx = this.x, vy = this.y, vz = this.z;
  4125. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4126. // t = 2 * cross( q.xyz, v );
  4127. const tx = 2 * ( qy * vz - qz * vy );
  4128. const ty = 2 * ( qz * vx - qx * vz );
  4129. const tz = 2 * ( qx * vy - qy * vx );
  4130. // v + q.w * t + cross( q.xyz, t );
  4131. this.x = vx + qw * tx + qy * tz - qz * ty;
  4132. this.y = vy + qw * ty + qz * tx - qx * tz;
  4133. this.z = vz + qw * tz + qx * ty - qy * tx;
  4134. return this;
  4135. }
  4136. /**
  4137. * Projects this vector from world space into the camera's normalized
  4138. * device coordinate (NDC) space.
  4139. *
  4140. * @param {Camera} camera - The camera.
  4141. * @return {Vector3} A reference to this vector.
  4142. */
  4143. project( camera ) {
  4144. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4145. }
  4146. /**
  4147. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4148. * space into world space.
  4149. *
  4150. * @param {Camera} camera - The camera.
  4151. * @return {Vector3} A reference to this vector.
  4152. */
  4153. unproject( camera ) {
  4154. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4155. }
  4156. /**
  4157. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4158. * subset of the given 4x4 matrix and then normalizes the result.
  4159. *
  4160. * @param {Matrix4} m - The matrix.
  4161. * @return {Vector3} A reference to this vector.
  4162. */
  4163. transformDirection( m ) {
  4164. // input: THREE.Matrix4 affine matrix
  4165. // vector interpreted as a direction
  4166. const x = this.x, y = this.y, z = this.z;
  4167. const e = m.elements;
  4168. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4169. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4170. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4171. return this.normalize();
  4172. }
  4173. /**
  4174. * Divides this instance by the given vector.
  4175. *
  4176. * @param {Vector3} v - The vector to divide.
  4177. * @return {Vector3} A reference to this vector.
  4178. */
  4179. divide( v ) {
  4180. this.x /= v.x;
  4181. this.y /= v.y;
  4182. this.z /= v.z;
  4183. return this;
  4184. }
  4185. /**
  4186. * Divides this vector by the given scalar.
  4187. *
  4188. * @param {number} scalar - The scalar to divide.
  4189. * @return {Vector3} A reference to this vector.
  4190. */
  4191. divideScalar( scalar ) {
  4192. return this.multiplyScalar( 1 / scalar );
  4193. }
  4194. /**
  4195. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4196. * value, replace that value with the corresponding min value.
  4197. *
  4198. * @param {Vector3} v - The vector.
  4199. * @return {Vector3} A reference to this vector.
  4200. */
  4201. min( v ) {
  4202. this.x = Math.min( this.x, v.x );
  4203. this.y = Math.min( this.y, v.y );
  4204. this.z = Math.min( this.z, v.z );
  4205. return this;
  4206. }
  4207. /**
  4208. * If this vector's x, y or z value is less than the given vector's x, y or z
  4209. * value, replace that value with the corresponding max value.
  4210. *
  4211. * @param {Vector3} v - The vector.
  4212. * @return {Vector3} A reference to this vector.
  4213. */
  4214. max( v ) {
  4215. this.x = Math.max( this.x, v.x );
  4216. this.y = Math.max( this.y, v.y );
  4217. this.z = Math.max( this.z, v.z );
  4218. return this;
  4219. }
  4220. /**
  4221. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4222. * value, it is replaced by the corresponding value.
  4223. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4224. * it is replaced by the corresponding value.
  4225. *
  4226. * @param {Vector3} min - The minimum x, y and z values.
  4227. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4228. * @return {Vector3} A reference to this vector.
  4229. */
  4230. clamp( min, max ) {
  4231. // assumes min < max, componentwise
  4232. this.x = clamp( this.x, min.x, max.x );
  4233. this.y = clamp( this.y, min.y, max.y );
  4234. this.z = clamp( this.z, min.z, max.z );
  4235. return this;
  4236. }
  4237. /**
  4238. * If this vector's x, y or z values are greater than the max value, they are
  4239. * replaced by the max value.
  4240. * If this vector's x, y or z values are less than the min value, they are
  4241. * replaced by the min value.
  4242. *
  4243. * @param {number} minVal - The minimum value the components will be clamped to.
  4244. * @param {number} maxVal - The maximum value the components will be clamped to.
  4245. * @return {Vector3} A reference to this vector.
  4246. */
  4247. clampScalar( minVal, maxVal ) {
  4248. this.x = clamp( this.x, minVal, maxVal );
  4249. this.y = clamp( this.y, minVal, maxVal );
  4250. this.z = clamp( this.z, minVal, maxVal );
  4251. return this;
  4252. }
  4253. /**
  4254. * If this vector's length is greater than the max value, it is replaced by
  4255. * the max value.
  4256. * If this vector's length is less than the min value, it is replaced by the
  4257. * min value.
  4258. *
  4259. * @param {number} min - The minimum value the vector length will be clamped to.
  4260. * @param {number} max - The maximum value the vector length will be clamped to.
  4261. * @return {Vector3} A reference to this vector.
  4262. */
  4263. clampLength( min, max ) {
  4264. const length = this.length();
  4265. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4266. }
  4267. /**
  4268. * The components of this vector are rounded down to the nearest integer value.
  4269. *
  4270. * @return {Vector3} A reference to this vector.
  4271. */
  4272. floor() {
  4273. this.x = Math.floor( this.x );
  4274. this.y = Math.floor( this.y );
  4275. this.z = Math.floor( this.z );
  4276. return this;
  4277. }
  4278. /**
  4279. * The components of this vector are rounded up to the nearest integer value.
  4280. *
  4281. * @return {Vector3} A reference to this vector.
  4282. */
  4283. ceil() {
  4284. this.x = Math.ceil( this.x );
  4285. this.y = Math.ceil( this.y );
  4286. this.z = Math.ceil( this.z );
  4287. return this;
  4288. }
  4289. /**
  4290. * The components of this vector are rounded to the nearest integer value
  4291. *
  4292. * @return {Vector3} A reference to this vector.
  4293. */
  4294. round() {
  4295. this.x = Math.round( this.x );
  4296. this.y = Math.round( this.y );
  4297. this.z = Math.round( this.z );
  4298. return this;
  4299. }
  4300. /**
  4301. * The components of this vector are rounded towards zero (up if negative,
  4302. * down if positive) to an integer value.
  4303. *
  4304. * @return {Vector3} A reference to this vector.
  4305. */
  4306. roundToZero() {
  4307. this.x = Math.trunc( this.x );
  4308. this.y = Math.trunc( this.y );
  4309. this.z = Math.trunc( this.z );
  4310. return this;
  4311. }
  4312. /**
  4313. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4314. *
  4315. * @return {Vector3} A reference to this vector.
  4316. */
  4317. negate() {
  4318. this.x = - this.x;
  4319. this.y = - this.y;
  4320. this.z = - this.z;
  4321. return this;
  4322. }
  4323. /**
  4324. * Calculates the dot product of the given vector with this instance.
  4325. *
  4326. * @param {Vector3} v - The vector to compute the dot product with.
  4327. * @return {number} The result of the dot product.
  4328. */
  4329. dot( v ) {
  4330. return this.x * v.x + this.y * v.y + this.z * v.z;
  4331. }
  4332. /**
  4333. * Computes the square of the Euclidean length (straight-line length) from
  4334. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4335. * compare the length squared instead as it is slightly more efficient to calculate.
  4336. *
  4337. * @return {number} The square length of this vector.
  4338. */
  4339. lengthSq() {
  4340. return this.x * this.x + this.y * this.y + this.z * this.z;
  4341. }
  4342. /**
  4343. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4344. *
  4345. * @return {number} The length of this vector.
  4346. */
  4347. length() {
  4348. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4349. }
  4350. /**
  4351. * Computes the Manhattan length of this vector.
  4352. *
  4353. * @return {number} The length of this vector.
  4354. */
  4355. manhattanLength() {
  4356. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4357. }
  4358. /**
  4359. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4360. * with the same direction as this one, but with a vector length of `1`.
  4361. *
  4362. * @return {Vector3} A reference to this vector.
  4363. */
  4364. normalize() {
  4365. return this.divideScalar( this.length() || 1 );
  4366. }
  4367. /**
  4368. * Sets this vector to a vector with the same direction as this one, but
  4369. * with the specified length.
  4370. *
  4371. * @param {number} length - The new length of this vector.
  4372. * @return {Vector3} A reference to this vector.
  4373. */
  4374. setLength( length ) {
  4375. return this.normalize().multiplyScalar( length );
  4376. }
  4377. /**
  4378. * Linearly interpolates between the given vector and this instance, where
  4379. * alpha is the percent distance along the line - alpha = 0 will be this
  4380. * vector, and alpha = 1 will be the given one.
  4381. *
  4382. * @param {Vector3} v - The vector to interpolate towards.
  4383. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4384. * @return {Vector3} A reference to this vector.
  4385. */
  4386. lerp( v, alpha ) {
  4387. this.x += ( v.x - this.x ) * alpha;
  4388. this.y += ( v.y - this.y ) * alpha;
  4389. this.z += ( v.z - this.z ) * alpha;
  4390. return this;
  4391. }
  4392. /**
  4393. * Linearly interpolates between the given vectors, where alpha is the percent
  4394. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4395. * be the second one. The result is stored in this instance.
  4396. *
  4397. * @param {Vector3} v1 - The first vector.
  4398. * @param {Vector3} v2 - The second vector.
  4399. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4400. * @return {Vector3} A reference to this vector.
  4401. */
  4402. lerpVectors( v1, v2, alpha ) {
  4403. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4404. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4405. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4406. return this;
  4407. }
  4408. /**
  4409. * Calculates the cross product of the given vector with this instance.
  4410. *
  4411. * @param {Vector3} v - The vector to compute the cross product with.
  4412. * @return {Vector3} The result of the cross product.
  4413. */
  4414. cross( v ) {
  4415. return this.crossVectors( this, v );
  4416. }
  4417. /**
  4418. * Calculates the cross product of the given vectors and stores the result
  4419. * in this instance.
  4420. *
  4421. * @param {Vector3} a - The first vector.
  4422. * @param {Vector3} b - The second vector.
  4423. * @return {Vector3} A reference to this vector.
  4424. */
  4425. crossVectors( a, b ) {
  4426. const ax = a.x, ay = a.y, az = a.z;
  4427. const bx = b.x, by = b.y, bz = b.z;
  4428. this.x = ay * bz - az * by;
  4429. this.y = az * bx - ax * bz;
  4430. this.z = ax * by - ay * bx;
  4431. return this;
  4432. }
  4433. /**
  4434. * Projects this vector onto the given one.
  4435. *
  4436. * @param {Vector3} v - The vector to project to.
  4437. * @return {Vector3} A reference to this vector.
  4438. */
  4439. projectOnVector( v ) {
  4440. const denominator = v.lengthSq();
  4441. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4442. const scalar = v.dot( this ) / denominator;
  4443. return this.copy( v ).multiplyScalar( scalar );
  4444. }
  4445. /**
  4446. * Projects this vector onto a plane by subtracting this
  4447. * vector projected onto the plane's normal from this vector.
  4448. *
  4449. * @param {Vector3} planeNormal - The plane normal.
  4450. * @return {Vector3} A reference to this vector.
  4451. */
  4452. projectOnPlane( planeNormal ) {
  4453. _vector$c.copy( this ).projectOnVector( planeNormal );
  4454. return this.sub( _vector$c );
  4455. }
  4456. /**
  4457. * Reflects this vector off a plane orthogonal to the given normal vector.
  4458. *
  4459. * @param {Vector3} normal - The (normalized) normal vector.
  4460. * @return {Vector3} A reference to this vector.
  4461. */
  4462. reflect( normal ) {
  4463. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4464. }
  4465. /**
  4466. * Returns the angle between the given vector and this instance in radians.
  4467. *
  4468. * @param {Vector3} v - The vector to compute the angle with.
  4469. * @return {number} The angle in radians.
  4470. */
  4471. angleTo( v ) {
  4472. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4473. if ( denominator === 0 ) return Math.PI / 2;
  4474. const theta = this.dot( v ) / denominator;
  4475. // clamp, to handle numerical problems
  4476. return Math.acos( clamp( theta, -1, 1 ) );
  4477. }
  4478. /**
  4479. * Computes the distance from the given vector to this instance.
  4480. *
  4481. * @param {Vector3} v - The vector to compute the distance to.
  4482. * @return {number} The distance.
  4483. */
  4484. distanceTo( v ) {
  4485. return Math.sqrt( this.distanceToSquared( v ) );
  4486. }
  4487. /**
  4488. * Computes the squared distance from the given vector to this instance.
  4489. * If you are just comparing the distance with another distance, you should compare
  4490. * the distance squared instead as it is slightly more efficient to calculate.
  4491. *
  4492. * @param {Vector3} v - The vector to compute the squared distance to.
  4493. * @return {number} The squared distance.
  4494. */
  4495. distanceToSquared( v ) {
  4496. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4497. return dx * dx + dy * dy + dz * dz;
  4498. }
  4499. /**
  4500. * Computes the Manhattan distance from the given vector to this instance.
  4501. *
  4502. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4503. * @return {number} The Manhattan distance.
  4504. */
  4505. manhattanDistanceTo( v ) {
  4506. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4507. }
  4508. /**
  4509. * Sets the vector components from the given spherical coordinates.
  4510. *
  4511. * @param {Spherical} s - The spherical coordinates.
  4512. * @return {Vector3} A reference to this vector.
  4513. */
  4514. setFromSpherical( s ) {
  4515. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4516. }
  4517. /**
  4518. * Sets the vector components from the given spherical coordinates.
  4519. *
  4520. * @param {number} radius - The radius.
  4521. * @param {number} phi - The phi angle in radians.
  4522. * @param {number} theta - The theta angle in radians.
  4523. * @return {Vector3} A reference to this vector.
  4524. */
  4525. setFromSphericalCoords( radius, phi, theta ) {
  4526. const sinPhiRadius = Math.sin( phi ) * radius;
  4527. this.x = sinPhiRadius * Math.sin( theta );
  4528. this.y = Math.cos( phi ) * radius;
  4529. this.z = sinPhiRadius * Math.cos( theta );
  4530. return this;
  4531. }
  4532. /**
  4533. * Sets the vector components from the given cylindrical coordinates.
  4534. *
  4535. * @param {Cylindrical} c - The cylindrical coordinates.
  4536. * @return {Vector3} A reference to this vector.
  4537. */
  4538. setFromCylindrical( c ) {
  4539. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4540. }
  4541. /**
  4542. * Sets the vector components from the given cylindrical coordinates.
  4543. *
  4544. * @param {number} radius - The radius.
  4545. * @param {number} theta - The theta angle in radians.
  4546. * @param {number} y - The y value.
  4547. * @return {Vector3} A reference to this vector.
  4548. */
  4549. setFromCylindricalCoords( radius, theta, y ) {
  4550. this.x = radius * Math.sin( theta );
  4551. this.y = y;
  4552. this.z = radius * Math.cos( theta );
  4553. return this;
  4554. }
  4555. /**
  4556. * Sets the vector components to the position elements of the
  4557. * given transformation matrix.
  4558. *
  4559. * @param {Matrix4} m - The 4x4 matrix.
  4560. * @return {Vector3} A reference to this vector.
  4561. */
  4562. setFromMatrixPosition( m ) {
  4563. const e = m.elements;
  4564. this.x = e[ 12 ];
  4565. this.y = e[ 13 ];
  4566. this.z = e[ 14 ];
  4567. return this;
  4568. }
  4569. /**
  4570. * Sets the vector components to the scale elements of the
  4571. * given transformation matrix.
  4572. *
  4573. * @param {Matrix4} m - The 4x4 matrix.
  4574. * @return {Vector3} A reference to this vector.
  4575. */
  4576. setFromMatrixScale( m ) {
  4577. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4578. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4579. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4580. this.x = sx;
  4581. this.y = sy;
  4582. this.z = sz;
  4583. return this;
  4584. }
  4585. /**
  4586. * Sets the vector components from the specified matrix column.
  4587. *
  4588. * @param {Matrix4} m - The 4x4 matrix.
  4589. * @param {number} index - The column index.
  4590. * @return {Vector3} A reference to this vector.
  4591. */
  4592. setFromMatrixColumn( m, index ) {
  4593. return this.fromArray( m.elements, index * 4 );
  4594. }
  4595. /**
  4596. * Sets the vector components from the specified matrix column.
  4597. *
  4598. * @param {Matrix3} m - The 3x3 matrix.
  4599. * @param {number} index - The column index.
  4600. * @return {Vector3} A reference to this vector.
  4601. */
  4602. setFromMatrix3Column( m, index ) {
  4603. return this.fromArray( m.elements, index * 3 );
  4604. }
  4605. /**
  4606. * Sets the vector components from the given Euler angles.
  4607. *
  4608. * @param {Euler} e - The Euler angles to set.
  4609. * @return {Vector3} A reference to this vector.
  4610. */
  4611. setFromEuler( e ) {
  4612. this.x = e._x;
  4613. this.y = e._y;
  4614. this.z = e._z;
  4615. return this;
  4616. }
  4617. /**
  4618. * Sets the vector components from the RGB components of the
  4619. * given color.
  4620. *
  4621. * @param {Color} c - The color to set.
  4622. * @return {Vector3} A reference to this vector.
  4623. */
  4624. setFromColor( c ) {
  4625. this.x = c.r;
  4626. this.y = c.g;
  4627. this.z = c.b;
  4628. return this;
  4629. }
  4630. /**
  4631. * Returns `true` if this vector is equal with the given one.
  4632. *
  4633. * @param {Vector3} v - The vector to test for equality.
  4634. * @return {boolean} Whether this vector is equal with the given one.
  4635. */
  4636. equals( v ) {
  4637. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4638. }
  4639. /**
  4640. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4641. * and z value to be `array[ offset + 2 ]`.
  4642. *
  4643. * @param {Array<number>} array - An array holding the vector component values.
  4644. * @param {number} [offset=0] - The offset into the array.
  4645. * @return {Vector3} A reference to this vector.
  4646. */
  4647. fromArray( array, offset = 0 ) {
  4648. this.x = array[ offset ];
  4649. this.y = array[ offset + 1 ];
  4650. this.z = array[ offset + 2 ];
  4651. return this;
  4652. }
  4653. /**
  4654. * Writes the components of this vector to the given array. If no array is provided,
  4655. * the method returns a new instance.
  4656. *
  4657. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4658. * @param {number} [offset=0] - Index of the first element in the array.
  4659. * @return {Array<number>} The vector components.
  4660. */
  4661. toArray( array = [], offset = 0 ) {
  4662. array[ offset ] = this.x;
  4663. array[ offset + 1 ] = this.y;
  4664. array[ offset + 2 ] = this.z;
  4665. return array;
  4666. }
  4667. /**
  4668. * Sets the components of this vector from the given buffer attribute.
  4669. *
  4670. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4671. * @param {number} index - The index into the attribute.
  4672. * @return {Vector3} A reference to this vector.
  4673. */
  4674. fromBufferAttribute( attribute, index ) {
  4675. this.x = attribute.getX( index );
  4676. this.y = attribute.getY( index );
  4677. this.z = attribute.getZ( index );
  4678. return this;
  4679. }
  4680. /**
  4681. * Sets each component of this vector to a pseudo-random value between `0` and
  4682. * `1`, excluding `1`.
  4683. *
  4684. * @return {Vector3} A reference to this vector.
  4685. */
  4686. random() {
  4687. this.x = Math.random();
  4688. this.y = Math.random();
  4689. this.z = Math.random();
  4690. return this;
  4691. }
  4692. /**
  4693. * Sets this vector to a uniformly random point on a unit sphere.
  4694. *
  4695. * @return {Vector3} A reference to this vector.
  4696. */
  4697. randomDirection() {
  4698. // https://mathworld.wolfram.com/SpherePointPicking.html
  4699. const theta = Math.random() * Math.PI * 2;
  4700. const u = Math.random() * 2 - 1;
  4701. const c = Math.sqrt( 1 - u * u );
  4702. this.x = c * Math.cos( theta );
  4703. this.y = u;
  4704. this.z = c * Math.sin( theta );
  4705. return this;
  4706. }
  4707. *[ Symbol.iterator ]() {
  4708. yield this.x;
  4709. yield this.y;
  4710. yield this.z;
  4711. }
  4712. }
  4713. const _vector$c = /*@__PURE__*/ new Vector3();
  4714. const _quaternion$5 = /*@__PURE__*/ new Quaternion();
  4715. /**
  4716. * Represents a 3x3 matrix.
  4717. *
  4718. * A Note on Row-Major and Column-Major Ordering:
  4719. *
  4720. * The constructor and {@link Matrix3#set} method take arguments in
  4721. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4722. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4723. * This means that calling:
  4724. * ```js
  4725. * const m = new THREE.Matrix();
  4726. * m.set( 11, 12, 13,
  4727. * 21, 22, 23,
  4728. * 31, 32, 33 );
  4729. * ```
  4730. * will result in the elements array containing:
  4731. * ```js
  4732. * m.elements = [ 11, 21, 31,
  4733. * 12, 22, 32,
  4734. * 13, 23, 33 ];
  4735. * ```
  4736. * and internally all calculations are performed using column-major ordering.
  4737. * However, as the actual ordering makes no difference mathematically and
  4738. * most people are used to thinking about matrices in row-major order, the
  4739. * three.js documentation shows matrices in row-major order. Just bear in
  4740. * mind that if you are reading the source code, you'll have to take the
  4741. * transpose of any matrices outlined here to make sense of the calculations.
  4742. */
  4743. class Matrix3 {
  4744. /**
  4745. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4746. * in row-major order. If no arguments are provided, the constructor
  4747. * initializes the matrix as an identity matrix.
  4748. *
  4749. * @param {number} [n11] - 1-1 matrix element.
  4750. * @param {number} [n12] - 1-2 matrix element.
  4751. * @param {number} [n13] - 1-3 matrix element.
  4752. * @param {number} [n21] - 2-1 matrix element.
  4753. * @param {number} [n22] - 2-2 matrix element.
  4754. * @param {number} [n23] - 2-3 matrix element.
  4755. * @param {number} [n31] - 3-1 matrix element.
  4756. * @param {number} [n32] - 3-2 matrix element.
  4757. * @param {number} [n33] - 3-3 matrix element.
  4758. */
  4759. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4760. /**
  4761. * This flag can be used for type testing.
  4762. *
  4763. * @type {boolean}
  4764. * @readonly
  4765. * @default true
  4766. */
  4767. Matrix3.prototype.isMatrix3 = true;
  4768. /**
  4769. * A column-major list of matrix values.
  4770. *
  4771. * @type {Array<number>}
  4772. */
  4773. this.elements = [
  4774. 1, 0, 0,
  4775. 0, 1, 0,
  4776. 0, 0, 1
  4777. ];
  4778. if ( n11 !== undefined ) {
  4779. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4780. }
  4781. }
  4782. /**
  4783. * Sets the elements of the matrix.The arguments are supposed to be
  4784. * in row-major order.
  4785. *
  4786. * @param {number} [n11] - 1-1 matrix element.
  4787. * @param {number} [n12] - 1-2 matrix element.
  4788. * @param {number} [n13] - 1-3 matrix element.
  4789. * @param {number} [n21] - 2-1 matrix element.
  4790. * @param {number} [n22] - 2-2 matrix element.
  4791. * @param {number} [n23] - 2-3 matrix element.
  4792. * @param {number} [n31] - 3-1 matrix element.
  4793. * @param {number} [n32] - 3-2 matrix element.
  4794. * @param {number} [n33] - 3-3 matrix element.
  4795. * @return {Matrix3} A reference to this matrix.
  4796. */
  4797. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4798. const te = this.elements;
  4799. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4800. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4801. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4802. return this;
  4803. }
  4804. /**
  4805. * Sets this matrix to the 3x3 identity matrix.
  4806. *
  4807. * @return {Matrix3} A reference to this matrix.
  4808. */
  4809. identity() {
  4810. this.set(
  4811. 1, 0, 0,
  4812. 0, 1, 0,
  4813. 0, 0, 1
  4814. );
  4815. return this;
  4816. }
  4817. /**
  4818. * Copies the values of the given matrix to this instance.
  4819. *
  4820. * @param {Matrix3} m - The matrix to copy.
  4821. * @return {Matrix3} A reference to this matrix.
  4822. */
  4823. copy( m ) {
  4824. const te = this.elements;
  4825. const me = m.elements;
  4826. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4827. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4828. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4829. return this;
  4830. }
  4831. /**
  4832. * Extracts the basis of this matrix into the three axis vectors provided.
  4833. *
  4834. * @param {Vector3} xAxis - The basis's x axis.
  4835. * @param {Vector3} yAxis - The basis's y axis.
  4836. * @param {Vector3} zAxis - The basis's z axis.
  4837. * @return {Matrix3} A reference to this matrix.
  4838. */
  4839. extractBasis( xAxis, yAxis, zAxis ) {
  4840. xAxis.setFromMatrix3Column( this, 0 );
  4841. yAxis.setFromMatrix3Column( this, 1 );
  4842. zAxis.setFromMatrix3Column( this, 2 );
  4843. return this;
  4844. }
  4845. /**
  4846. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4847. *
  4848. * @param {Matrix4} m - The 4x4 matrix.
  4849. * @return {Matrix3} A reference to this matrix.
  4850. */
  4851. setFromMatrix4( m ) {
  4852. const me = m.elements;
  4853. this.set(
  4854. me[ 0 ], me[ 4 ], me[ 8 ],
  4855. me[ 1 ], me[ 5 ], me[ 9 ],
  4856. me[ 2 ], me[ 6 ], me[ 10 ]
  4857. );
  4858. return this;
  4859. }
  4860. /**
  4861. * Post-multiplies this matrix by the given 3x3 matrix.
  4862. *
  4863. * @param {Matrix3} m - The matrix to multiply with.
  4864. * @return {Matrix3} A reference to this matrix.
  4865. */
  4866. multiply( m ) {
  4867. return this.multiplyMatrices( this, m );
  4868. }
  4869. /**
  4870. * Pre-multiplies this matrix by the given 3x3 matrix.
  4871. *
  4872. * @param {Matrix3} m - The matrix to multiply with.
  4873. * @return {Matrix3} A reference to this matrix.
  4874. */
  4875. premultiply( m ) {
  4876. return this.multiplyMatrices( m, this );
  4877. }
  4878. /**
  4879. * Multiples the given 3x3 matrices and stores the result
  4880. * in this matrix.
  4881. *
  4882. * @param {Matrix3} a - The first matrix.
  4883. * @param {Matrix3} b - The second matrix.
  4884. * @return {Matrix3} A reference to this matrix.
  4885. */
  4886. multiplyMatrices( a, b ) {
  4887. const ae = a.elements;
  4888. const be = b.elements;
  4889. const te = this.elements;
  4890. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4891. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4892. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4893. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4894. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4895. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4896. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4897. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4898. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4899. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4900. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4901. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4902. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4903. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4904. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4905. return this;
  4906. }
  4907. /**
  4908. * Multiplies every component of the matrix by the given scalar.
  4909. *
  4910. * @param {number} s - The scalar.
  4911. * @return {Matrix3} A reference to this matrix.
  4912. */
  4913. multiplyScalar( s ) {
  4914. const te = this.elements;
  4915. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4916. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4917. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4918. return this;
  4919. }
  4920. /**
  4921. * Computes and returns the determinant of this matrix.
  4922. *
  4923. * @return {number} The determinant.
  4924. */
  4925. determinant() {
  4926. const te = this.elements;
  4927. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4928. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4929. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4930. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4931. }
  4932. /**
  4933. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4934. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4935. * a zero matrix instead.
  4936. *
  4937. * @return {Matrix3} A reference to this matrix.
  4938. */
  4939. invert() {
  4940. const te = this.elements,
  4941. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4942. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4943. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4944. t11 = n33 * n22 - n32 * n23,
  4945. t12 = n32 * n13 - n33 * n12,
  4946. t13 = n23 * n12 - n22 * n13,
  4947. det = n11 * t11 + n21 * t12 + n31 * t13;
  4948. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4949. const detInv = 1 / det;
  4950. te[ 0 ] = t11 * detInv;
  4951. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4952. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4953. te[ 3 ] = t12 * detInv;
  4954. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4955. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4956. te[ 6 ] = t13 * detInv;
  4957. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4958. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4959. return this;
  4960. }
  4961. /**
  4962. * Transposes this matrix in place.
  4963. *
  4964. * @return {Matrix3} A reference to this matrix.
  4965. */
  4966. transpose() {
  4967. let tmp;
  4968. const m = this.elements;
  4969. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4970. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4971. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4972. return this;
  4973. }
  4974. /**
  4975. * Computes the normal matrix which is the inverse transpose of the upper
  4976. * left 3x3 portion of the given 4x4 matrix.
  4977. *
  4978. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4979. * @return {Matrix3} A reference to this matrix.
  4980. */
  4981. getNormalMatrix( matrix4 ) {
  4982. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4983. }
  4984. /**
  4985. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4986. *
  4987. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4988. * @return {Matrix3} A reference to this matrix.
  4989. */
  4990. transposeIntoArray( r ) {
  4991. const m = this.elements;
  4992. r[ 0 ] = m[ 0 ];
  4993. r[ 1 ] = m[ 3 ];
  4994. r[ 2 ] = m[ 6 ];
  4995. r[ 3 ] = m[ 1 ];
  4996. r[ 4 ] = m[ 4 ];
  4997. r[ 5 ] = m[ 7 ];
  4998. r[ 6 ] = m[ 2 ];
  4999. r[ 7 ] = m[ 5 ];
  5000. r[ 8 ] = m[ 8 ];
  5001. return this;
  5002. }
  5003. /**
  5004. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  5005. *
  5006. * @param {number} tx - Offset x.
  5007. * @param {number} ty - Offset y.
  5008. * @param {number} sx - Repeat x.
  5009. * @param {number} sy - Repeat y.
  5010. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5011. * @param {number} cx - Center x of rotation.
  5012. * @param {number} cy - Center y of rotation
  5013. * @return {Matrix3} A reference to this matrix.
  5014. */
  5015. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5016. const c = Math.cos( rotation );
  5017. const s = Math.sin( rotation );
  5018. this.set(
  5019. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5020. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5021. 0, 0, 1
  5022. );
  5023. return this;
  5024. }
  5025. /**
  5026. * Scales this matrix with the given scalar values.
  5027. *
  5028. * @param {number} sx - The amount to scale in the X axis.
  5029. * @param {number} sy - The amount to scale in the Y axis.
  5030. * @return {Matrix3} A reference to this matrix.
  5031. */
  5032. scale( sx, sy ) {
  5033. this.premultiply( _m3.makeScale( sx, sy ) );
  5034. return this;
  5035. }
  5036. /**
  5037. * Rotates this matrix by the given angle.
  5038. *
  5039. * @param {number} theta - The rotation in radians.
  5040. * @return {Matrix3} A reference to this matrix.
  5041. */
  5042. rotate( theta ) {
  5043. this.premultiply( _m3.makeRotation( - theta ) );
  5044. return this;
  5045. }
  5046. /**
  5047. * Translates this matrix by the given scalar values.
  5048. *
  5049. * @param {number} tx - The amount to translate in the X axis.
  5050. * @param {number} ty - The amount to translate in the Y axis.
  5051. * @return {Matrix3} A reference to this matrix.
  5052. */
  5053. translate( tx, ty ) {
  5054. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5055. return this;
  5056. }
  5057. // for 2D Transforms
  5058. /**
  5059. * Sets this matrix as a 2D translation transform.
  5060. *
  5061. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5062. * @param {number} y - The amount to translate in the Y axis.
  5063. * @return {Matrix3} A reference to this matrix.
  5064. */
  5065. makeTranslation( x, y ) {
  5066. if ( x.isVector2 ) {
  5067. this.set(
  5068. 1, 0, x.x,
  5069. 0, 1, x.y,
  5070. 0, 0, 1
  5071. );
  5072. } else {
  5073. this.set(
  5074. 1, 0, x,
  5075. 0, 1, y,
  5076. 0, 0, 1
  5077. );
  5078. }
  5079. return this;
  5080. }
  5081. /**
  5082. * Sets this matrix as a 2D rotational transformation.
  5083. *
  5084. * @param {number} theta - The rotation in radians.
  5085. * @return {Matrix3} A reference to this matrix.
  5086. */
  5087. makeRotation( theta ) {
  5088. // counterclockwise
  5089. const c = Math.cos( theta );
  5090. const s = Math.sin( theta );
  5091. this.set(
  5092. c, - s, 0,
  5093. s, c, 0,
  5094. 0, 0, 1
  5095. );
  5096. return this;
  5097. }
  5098. /**
  5099. * Sets this matrix as a 2D scale transform.
  5100. *
  5101. * @param {number} x - The amount to scale in the X axis.
  5102. * @param {number} y - The amount to scale in the Y axis.
  5103. * @return {Matrix3} A reference to this matrix.
  5104. */
  5105. makeScale( x, y ) {
  5106. this.set(
  5107. x, 0, 0,
  5108. 0, y, 0,
  5109. 0, 0, 1
  5110. );
  5111. return this;
  5112. }
  5113. /**
  5114. * Returns `true` if this matrix is equal with the given one.
  5115. *
  5116. * @param {Matrix3} matrix - The matrix to test for equality.
  5117. * @return {boolean} Whether this matrix is equal with the given one.
  5118. */
  5119. equals( matrix ) {
  5120. const te = this.elements;
  5121. const me = matrix.elements;
  5122. for ( let i = 0; i < 9; i ++ ) {
  5123. if ( te[ i ] !== me[ i ] ) return false;
  5124. }
  5125. return true;
  5126. }
  5127. /**
  5128. * Sets the elements of the matrix from the given array.
  5129. *
  5130. * @param {Array<number>} array - The matrix elements in column-major order.
  5131. * @param {number} [offset=0] - Index of the first element in the array.
  5132. * @return {Matrix3} A reference to this matrix.
  5133. */
  5134. fromArray( array, offset = 0 ) {
  5135. for ( let i = 0; i < 9; i ++ ) {
  5136. this.elements[ i ] = array[ i + offset ];
  5137. }
  5138. return this;
  5139. }
  5140. /**
  5141. * Writes the elements of this matrix to the given array. If no array is provided,
  5142. * the method returns a new instance.
  5143. *
  5144. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5145. * @param {number} [offset=0] - Index of the first element in the array.
  5146. * @return {Array<number>} The matrix elements in column-major order.
  5147. */
  5148. toArray( array = [], offset = 0 ) {
  5149. const te = this.elements;
  5150. array[ offset ] = te[ 0 ];
  5151. array[ offset + 1 ] = te[ 1 ];
  5152. array[ offset + 2 ] = te[ 2 ];
  5153. array[ offset + 3 ] = te[ 3 ];
  5154. array[ offset + 4 ] = te[ 4 ];
  5155. array[ offset + 5 ] = te[ 5 ];
  5156. array[ offset + 6 ] = te[ 6 ];
  5157. array[ offset + 7 ] = te[ 7 ];
  5158. array[ offset + 8 ] = te[ 8 ];
  5159. return array;
  5160. }
  5161. /**
  5162. * Returns a matrix with copied values from this instance.
  5163. *
  5164. * @return {Matrix3} A clone of this instance.
  5165. */
  5166. clone() {
  5167. return new this.constructor().fromArray( this.elements );
  5168. }
  5169. }
  5170. const _m3 = /*@__PURE__*/ new Matrix3();
  5171. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5172. 0.4123908, 0.3575843, 0.1804808,
  5173. 0.2126390, 0.7151687, 0.0721923,
  5174. 0.0193308, 0.1191948, 0.9505322
  5175. );
  5176. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5177. 3.2409699, -1.5373832, -0.4986108,
  5178. -0.9692436, 1.8759675, 0.0415551,
  5179. 0.0556301, -0.203977, 1.0569715
  5180. );
  5181. function createColorManagement() {
  5182. const ColorManagement = {
  5183. enabled: true,
  5184. workingColorSpace: LinearSRGBColorSpace,
  5185. /**
  5186. * Implementations of supported color spaces.
  5187. *
  5188. * Required:
  5189. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5190. * - whitePoint: reference white [ x y ]
  5191. * - transfer: transfer function (pre-defined)
  5192. * - toXYZ: Matrix3 RGB to XYZ transform
  5193. * - fromXYZ: Matrix3 XYZ to RGB transform
  5194. * - luminanceCoefficients: RGB luminance coefficients
  5195. *
  5196. * Optional:
  5197. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5198. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5199. *
  5200. * Reference:
  5201. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5202. */
  5203. spaces: {},
  5204. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5205. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5206. return color;
  5207. }
  5208. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5209. color.r = SRGBToLinear( color.r );
  5210. color.g = SRGBToLinear( color.g );
  5211. color.b = SRGBToLinear( color.b );
  5212. }
  5213. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5214. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5215. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5216. }
  5217. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5218. color.r = LinearToSRGB( color.r );
  5219. color.g = LinearToSRGB( color.g );
  5220. color.b = LinearToSRGB( color.b );
  5221. }
  5222. return color;
  5223. },
  5224. workingToColorSpace: function ( color, targetColorSpace ) {
  5225. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5226. },
  5227. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5228. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5229. },
  5230. getPrimaries: function ( colorSpace ) {
  5231. return this.spaces[ colorSpace ].primaries;
  5232. },
  5233. getTransfer: function ( colorSpace ) {
  5234. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5235. return this.spaces[ colorSpace ].transfer;
  5236. },
  5237. getToneMappingMode: function ( colorSpace ) {
  5238. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5239. },
  5240. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5241. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5242. },
  5243. define: function ( colorSpaces ) {
  5244. Object.assign( this.spaces, colorSpaces );
  5245. },
  5246. // Internal APIs
  5247. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5248. return targetMatrix
  5249. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5250. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5251. },
  5252. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5253. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5254. },
  5255. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5256. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5257. },
  5258. // Deprecated
  5259. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5260. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5261. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5262. },
  5263. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5264. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5265. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5266. },
  5267. };
  5268. /******************************************************************************
  5269. * sRGB definitions
  5270. */
  5271. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5272. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5273. const D65 = [ 0.3127, 0.3290 ];
  5274. ColorManagement.define( {
  5275. [ LinearSRGBColorSpace ]: {
  5276. primaries: REC709_PRIMARIES,
  5277. whitePoint: D65,
  5278. transfer: LinearTransfer,
  5279. toXYZ: LINEAR_REC709_TO_XYZ,
  5280. fromXYZ: XYZ_TO_LINEAR_REC709,
  5281. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5282. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5283. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5284. },
  5285. [ SRGBColorSpace ]: {
  5286. primaries: REC709_PRIMARIES,
  5287. whitePoint: D65,
  5288. transfer: SRGBTransfer,
  5289. toXYZ: LINEAR_REC709_TO_XYZ,
  5290. fromXYZ: XYZ_TO_LINEAR_REC709,
  5291. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5292. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5293. },
  5294. } );
  5295. return ColorManagement;
  5296. }
  5297. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5298. function SRGBToLinear( c ) {
  5299. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5300. }
  5301. function LinearToSRGB( c ) {
  5302. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5303. }
  5304. let _canvas;
  5305. /**
  5306. * A class containing utility functions for images.
  5307. *
  5308. * @hideconstructor
  5309. */
  5310. class ImageUtils {
  5311. /**
  5312. * Returns a data URI containing a representation of the given image.
  5313. *
  5314. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5315. * @param {string} [type='image/png'] - Indicates the image format.
  5316. * @return {string} The data URI.
  5317. */
  5318. static getDataURL( image, type = 'image/png' ) {
  5319. if ( /^data:/i.test( image.src ) ) {
  5320. return image.src;
  5321. }
  5322. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5323. return image.src;
  5324. }
  5325. let canvas;
  5326. if ( image instanceof HTMLCanvasElement ) {
  5327. canvas = image;
  5328. } else {
  5329. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5330. _canvas.width = image.width;
  5331. _canvas.height = image.height;
  5332. const context = _canvas.getContext( '2d' );
  5333. if ( image instanceof ImageData ) {
  5334. context.putImageData( image, 0, 0 );
  5335. } else {
  5336. context.drawImage( image, 0, 0, image.width, image.height );
  5337. }
  5338. canvas = _canvas;
  5339. }
  5340. return canvas.toDataURL( type );
  5341. }
  5342. /**
  5343. * Converts the given sRGB image data to linear color space.
  5344. *
  5345. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5346. * @return {HTMLCanvasElement|Object} The converted image.
  5347. */
  5348. static sRGBToLinear( image ) {
  5349. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5350. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5351. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5352. const canvas = createElementNS( 'canvas' );
  5353. canvas.width = image.width;
  5354. canvas.height = image.height;
  5355. const context = canvas.getContext( '2d' );
  5356. context.drawImage( image, 0, 0, image.width, image.height );
  5357. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5358. const data = imageData.data;
  5359. for ( let i = 0; i < data.length; i ++ ) {
  5360. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5361. }
  5362. context.putImageData( imageData, 0, 0 );
  5363. return canvas;
  5364. } else if ( image.data ) {
  5365. const data = image.data.slice( 0 );
  5366. for ( let i = 0; i < data.length; i ++ ) {
  5367. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5368. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5369. } else {
  5370. // assuming float
  5371. data[ i ] = SRGBToLinear( data[ i ] );
  5372. }
  5373. }
  5374. return {
  5375. data: data,
  5376. width: image.width,
  5377. height: image.height
  5378. };
  5379. } else {
  5380. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5381. return image;
  5382. }
  5383. }
  5384. }
  5385. let _sourceId = 0;
  5386. /**
  5387. * Represents the data source of a texture.
  5388. *
  5389. * The main purpose of this class is to decouple the data definition from the texture
  5390. * definition so the same data can be used with multiple texture instances.
  5391. */
  5392. class Source {
  5393. /**
  5394. * Constructs a new video texture.
  5395. *
  5396. * @param {any} [data=null] - The data definition of a texture.
  5397. */
  5398. constructor( data = null ) {
  5399. /**
  5400. * This flag can be used for type testing.
  5401. *
  5402. * @type {boolean}
  5403. * @readonly
  5404. * @default true
  5405. */
  5406. this.isSource = true;
  5407. /**
  5408. * The ID of the source.
  5409. *
  5410. * @name Source#id
  5411. * @type {number}
  5412. * @readonly
  5413. */
  5414. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5415. /**
  5416. * The UUID of the source.
  5417. *
  5418. * @type {string}
  5419. * @readonly
  5420. */
  5421. this.uuid = generateUUID();
  5422. /**
  5423. * The data definition of a texture.
  5424. *
  5425. * @type {any}
  5426. */
  5427. this.data = data;
  5428. /**
  5429. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5430. * provides more control on how texture data should be processed. When `dataReady` is set
  5431. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5432. * the data into the GPU memory.
  5433. *
  5434. * @type {boolean}
  5435. * @default true
  5436. */
  5437. this.dataReady = true;
  5438. /**
  5439. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5440. *
  5441. * @type {number}
  5442. * @readonly
  5443. * @default 0
  5444. */
  5445. this.version = 0;
  5446. }
  5447. /**
  5448. * Returns the dimensions of the source into the given target vector.
  5449. *
  5450. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5451. * @return {(Vector2|Vector3)} The dimensions of the source.
  5452. */
  5453. getSize( target ) {
  5454. const data = this.data;
  5455. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5456. target.set( data.videoWidth, data.videoHeight, 0 );
  5457. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5458. target.set( data.displayHeight, data.displayWidth, 0 );
  5459. } else if ( data !== null ) {
  5460. target.set( data.width, data.height, data.depth || 0 );
  5461. } else {
  5462. target.set( 0, 0, 0 );
  5463. }
  5464. return target;
  5465. }
  5466. /**
  5467. * When the property is set to `true`, the engine allocates the memory
  5468. * for the texture (if necessary) and triggers the actual texture upload
  5469. * to the GPU next time the source is used.
  5470. *
  5471. * @type {boolean}
  5472. * @default false
  5473. * @param {boolean} value
  5474. */
  5475. set needsUpdate( value ) {
  5476. if ( value === true ) this.version ++;
  5477. }
  5478. /**
  5479. * Serializes the source into JSON.
  5480. *
  5481. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5482. * @return {Object} A JSON object representing the serialized source.
  5483. * @see {@link ObjectLoader#parse}
  5484. */
  5485. toJSON( meta ) {
  5486. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5487. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5488. return meta.images[ this.uuid ];
  5489. }
  5490. const output = {
  5491. uuid: this.uuid,
  5492. url: ''
  5493. };
  5494. const data = this.data;
  5495. if ( data !== null ) {
  5496. let url;
  5497. if ( Array.isArray( data ) ) {
  5498. // cube texture
  5499. url = [];
  5500. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5501. if ( data[ i ].isDataTexture ) {
  5502. url.push( serializeImage( data[ i ].image ) );
  5503. } else {
  5504. url.push( serializeImage( data[ i ] ) );
  5505. }
  5506. }
  5507. } else {
  5508. // texture
  5509. url = serializeImage( data );
  5510. }
  5511. output.url = url;
  5512. }
  5513. if ( ! isRootObject ) {
  5514. meta.images[ this.uuid ] = output;
  5515. }
  5516. return output;
  5517. }
  5518. }
  5519. function serializeImage( image ) {
  5520. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5521. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5522. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5523. // default images
  5524. return ImageUtils.getDataURL( image );
  5525. } else {
  5526. if ( image.data ) {
  5527. // images of DataTexture
  5528. return {
  5529. data: Array.from( image.data ),
  5530. width: image.width,
  5531. height: image.height,
  5532. type: image.data.constructor.name
  5533. };
  5534. } else {
  5535. warn( 'Texture: Unable to serialize Texture.' );
  5536. return {};
  5537. }
  5538. }
  5539. }
  5540. let _textureId = 0;
  5541. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5542. /**
  5543. * Base class for all textures.
  5544. *
  5545. * Note: After the initial use of a texture, its dimensions, format, and type
  5546. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5547. *
  5548. * @augments EventDispatcher
  5549. */
  5550. class Texture extends EventDispatcher {
  5551. /**
  5552. * Constructs a new texture.
  5553. *
  5554. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5555. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5556. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5557. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5558. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5559. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5560. * @param {number} [format=RGBAFormat] - The texture format.
  5561. * @param {number} [type=UnsignedByteType] - The texture type.
  5562. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5563. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5564. */
  5565. 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 ) {
  5566. super();
  5567. /**
  5568. * This flag can be used for type testing.
  5569. *
  5570. * @type {boolean}
  5571. * @readonly
  5572. * @default true
  5573. */
  5574. this.isTexture = true;
  5575. /**
  5576. * The ID of the texture.
  5577. *
  5578. * @name Texture#id
  5579. * @type {number}
  5580. * @readonly
  5581. */
  5582. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5583. /**
  5584. * The UUID of the texture.
  5585. *
  5586. * @type {string}
  5587. * @readonly
  5588. */
  5589. this.uuid = generateUUID();
  5590. /**
  5591. * The name of the texture.
  5592. *
  5593. * @type {string}
  5594. */
  5595. this.name = '';
  5596. /**
  5597. * The data definition of a texture. A reference to the data source can be
  5598. * shared across textures. This is often useful in context of spritesheets
  5599. * where multiple textures render the same data but with different texture
  5600. * transformations.
  5601. *
  5602. * @type {Source}
  5603. */
  5604. this.source = new Source( image );
  5605. /**
  5606. * An array holding user-defined mipmaps.
  5607. *
  5608. * @type {Array<Object>}
  5609. */
  5610. this.mipmaps = [];
  5611. /**
  5612. * How the texture is applied to the object. The value `UVMapping`
  5613. * is the default, where texture or uv coordinates are used to apply the map.
  5614. *
  5615. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5616. * @default UVMapping
  5617. */
  5618. this.mapping = mapping;
  5619. /**
  5620. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5621. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5622. *
  5623. * @type {number}
  5624. * @default 0
  5625. */
  5626. this.channel = 0;
  5627. /**
  5628. * This defines how the texture is wrapped horizontally and corresponds to
  5629. * *U* in UV mapping.
  5630. *
  5631. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5632. * @default ClampToEdgeWrapping
  5633. */
  5634. this.wrapS = wrapS;
  5635. /**
  5636. * This defines how the texture is wrapped horizontally and corresponds to
  5637. * *V* in UV mapping.
  5638. *
  5639. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5640. * @default ClampToEdgeWrapping
  5641. */
  5642. this.wrapT = wrapT;
  5643. /**
  5644. * How the texture is sampled when a texel covers more than one pixel.
  5645. *
  5646. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5647. * @default LinearFilter
  5648. */
  5649. this.magFilter = magFilter;
  5650. /**
  5651. * How the texture is sampled when a texel covers less than one pixel.
  5652. *
  5653. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5654. * @default LinearMipmapLinearFilter
  5655. */
  5656. this.minFilter = minFilter;
  5657. /**
  5658. * The number of samples taken along the axis through the pixel that has the
  5659. * highest density of texels. By default, this value is `1`. A higher value
  5660. * gives a less blurry result than a basic mipmap, at the cost of more
  5661. * texture samples being used.
  5662. *
  5663. * @type {number}
  5664. * @default Texture.DEFAULT_ANISOTROPY
  5665. */
  5666. this.anisotropy = anisotropy;
  5667. /**
  5668. * The format of the texture.
  5669. *
  5670. * @type {number}
  5671. * @default RGBAFormat
  5672. */
  5673. this.format = format;
  5674. /**
  5675. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5676. * defines how the texture data is going to be stored on the GPU.
  5677. *
  5678. * This property allows to overwrite the default format.
  5679. *
  5680. * @type {?string}
  5681. * @default null
  5682. */
  5683. this.internalFormat = null;
  5684. /**
  5685. * The data type of the texture.
  5686. *
  5687. * @type {number}
  5688. * @default UnsignedByteType
  5689. */
  5690. this.type = type;
  5691. /**
  5692. * How much a single repetition of the texture is offset from the beginning,
  5693. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5694. *
  5695. * @type {Vector2}
  5696. * @default (0,0)
  5697. */
  5698. this.offset = new Vector2( 0, 0 );
  5699. /**
  5700. * How many times the texture is repeated across the surface, in each
  5701. * direction U and V. If repeat is set greater than `1` in either direction,
  5702. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5703. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5704. *
  5705. * @type {Vector2}
  5706. * @default (1,1)
  5707. */
  5708. this.repeat = new Vector2( 1, 1 );
  5709. /**
  5710. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5711. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5712. *
  5713. * @type {Vector2}
  5714. * @default (0,0)
  5715. */
  5716. this.center = new Vector2( 0, 0 );
  5717. /**
  5718. * How much the texture is rotated around the center point, in radians.
  5719. * Positive values are counter-clockwise.
  5720. *
  5721. * @type {number}
  5722. * @default 0
  5723. */
  5724. this.rotation = 0;
  5725. /**
  5726. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5727. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5728. * {@link Texture#rotation}, and {@link Texture#center}.
  5729. *
  5730. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5731. *
  5732. * @type {boolean}
  5733. * @default true
  5734. */
  5735. this.matrixAutoUpdate = true;
  5736. /**
  5737. * The uv-transformation matrix of the texture.
  5738. *
  5739. * @type {Matrix3}
  5740. */
  5741. this.matrix = new Matrix3();
  5742. /**
  5743. * Whether to generate mipmaps (if possible) for a texture.
  5744. *
  5745. * Set this to `false` if you are creating mipmaps manually.
  5746. *
  5747. * @type {boolean}
  5748. * @default true
  5749. */
  5750. this.generateMipmaps = true;
  5751. /**
  5752. * If set to `true`, the alpha channel, if present, is multiplied into the
  5753. * color channels when the texture is uploaded to the GPU.
  5754. *
  5755. * Note that this property has no effect when using `ImageBitmap`. You need to
  5756. * configure premultiply alpha on bitmap creation instead.
  5757. *
  5758. * @type {boolean}
  5759. * @default false
  5760. */
  5761. this.premultiplyAlpha = false;
  5762. /**
  5763. * If set to `true`, the texture is flipped along the vertical axis when
  5764. * uploaded to the GPU.
  5765. *
  5766. * Note that this property has no effect when using `ImageBitmap`. You need to
  5767. * configure the flip on bitmap creation instead.
  5768. *
  5769. * @type {boolean}
  5770. * @default true
  5771. */
  5772. this.flipY = true;
  5773. /**
  5774. * Specifies the alignment requirements for the start of each pixel row in memory.
  5775. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5776. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5777. *
  5778. * @type {number}
  5779. * @default 4
  5780. */
  5781. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5782. /**
  5783. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5784. *
  5785. * @type {string}
  5786. * @default NoColorSpace
  5787. */
  5788. this.colorSpace = colorSpace;
  5789. /**
  5790. * An object that can be used to store custom data about the texture. It
  5791. * should not hold references to functions as these will not be cloned.
  5792. *
  5793. * @type {Object}
  5794. */
  5795. this.userData = {};
  5796. /**
  5797. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5798. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5799. *
  5800. * @type {Array<Object>}
  5801. */
  5802. this.updateRanges = [];
  5803. /**
  5804. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5805. *
  5806. * @type {number}
  5807. * @readonly
  5808. * @default 0
  5809. */
  5810. this.version = 0;
  5811. /**
  5812. * A callback function, called when the texture is updated (e.g., when
  5813. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5814. *
  5815. * @type {?Function}
  5816. * @default null
  5817. */
  5818. this.onUpdate = null;
  5819. /**
  5820. * An optional back reference to the textures render target.
  5821. *
  5822. * @type {?(RenderTarget|WebGLRenderTarget)}
  5823. * @default null
  5824. */
  5825. this.renderTarget = null;
  5826. /**
  5827. * Indicates whether a texture belongs to a render target or not.
  5828. *
  5829. * @type {boolean}
  5830. * @readonly
  5831. * @default false
  5832. */
  5833. this.isRenderTargetTexture = false;
  5834. /**
  5835. * Indicates if a texture should be handled like a texture array.
  5836. *
  5837. * @type {boolean}
  5838. * @readonly
  5839. * @default false
  5840. */
  5841. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5842. /**
  5843. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5844. * (only relevant for render target textures).
  5845. *
  5846. * @type {number}
  5847. * @readonly
  5848. * @default 0
  5849. */
  5850. this.pmremVersion = 0;
  5851. }
  5852. /**
  5853. * The width of the texture in pixels.
  5854. */
  5855. get width() {
  5856. return this.source.getSize( _tempVec3 ).x;
  5857. }
  5858. /**
  5859. * The height of the texture in pixels.
  5860. */
  5861. get height() {
  5862. return this.source.getSize( _tempVec3 ).y;
  5863. }
  5864. /**
  5865. * The depth of the texture in pixels.
  5866. */
  5867. get depth() {
  5868. return this.source.getSize( _tempVec3 ).z;
  5869. }
  5870. /**
  5871. * The image object holding the texture data.
  5872. *
  5873. * @type {?Object}
  5874. */
  5875. get image() {
  5876. return this.source.data;
  5877. }
  5878. set image( value = null ) {
  5879. this.source.data = value;
  5880. }
  5881. /**
  5882. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5883. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5884. */
  5885. updateMatrix() {
  5886. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5887. }
  5888. /**
  5889. * Adds a range of data in the data texture to be updated on the GPU.
  5890. *
  5891. * @param {number} start - Position at which to start update.
  5892. * @param {number} count - The number of components to update.
  5893. */
  5894. addUpdateRange( start, count ) {
  5895. this.updateRanges.push( { start, count } );
  5896. }
  5897. /**
  5898. * Clears the update ranges.
  5899. */
  5900. clearUpdateRanges() {
  5901. this.updateRanges.length = 0;
  5902. }
  5903. /**
  5904. * Returns a new texture with copied values from this instance.
  5905. *
  5906. * @return {Texture} A clone of this instance.
  5907. */
  5908. clone() {
  5909. return new this.constructor().copy( this );
  5910. }
  5911. /**
  5912. * Copies the values of the given texture to this instance.
  5913. *
  5914. * @param {Texture} source - The texture to copy.
  5915. * @return {Texture} A reference to this instance.
  5916. */
  5917. copy( source ) {
  5918. this.name = source.name;
  5919. this.source = source.source;
  5920. this.mipmaps = source.mipmaps.slice( 0 );
  5921. this.mapping = source.mapping;
  5922. this.channel = source.channel;
  5923. this.wrapS = source.wrapS;
  5924. this.wrapT = source.wrapT;
  5925. this.magFilter = source.magFilter;
  5926. this.minFilter = source.minFilter;
  5927. this.anisotropy = source.anisotropy;
  5928. this.format = source.format;
  5929. this.internalFormat = source.internalFormat;
  5930. this.type = source.type;
  5931. this.offset.copy( source.offset );
  5932. this.repeat.copy( source.repeat );
  5933. this.center.copy( source.center );
  5934. this.rotation = source.rotation;
  5935. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5936. this.matrix.copy( source.matrix );
  5937. this.generateMipmaps = source.generateMipmaps;
  5938. this.premultiplyAlpha = source.premultiplyAlpha;
  5939. this.flipY = source.flipY;
  5940. this.unpackAlignment = source.unpackAlignment;
  5941. this.colorSpace = source.colorSpace;
  5942. this.renderTarget = source.renderTarget;
  5943. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5944. this.isArrayTexture = source.isArrayTexture;
  5945. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5946. this.needsUpdate = true;
  5947. return this;
  5948. }
  5949. /**
  5950. * Sets this texture's properties based on `values`.
  5951. * @param {Object} values - A container with texture parameters.
  5952. */
  5953. setValues( values ) {
  5954. for ( const key in values ) {
  5955. const newValue = values[ key ];
  5956. if ( newValue === undefined ) {
  5957. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5958. continue;
  5959. }
  5960. const currentValue = this[ key ];
  5961. if ( currentValue === undefined ) {
  5962. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5963. continue;
  5964. }
  5965. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5966. currentValue.copy( newValue );
  5967. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5968. currentValue.copy( newValue );
  5969. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5970. currentValue.copy( newValue );
  5971. } else {
  5972. this[ key ] = newValue;
  5973. }
  5974. }
  5975. }
  5976. /**
  5977. * Serializes the texture into JSON.
  5978. *
  5979. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5980. * @return {Object} A JSON object representing the serialized texture.
  5981. * @see {@link ObjectLoader#parse}
  5982. */
  5983. toJSON( meta ) {
  5984. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5985. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5986. return meta.textures[ this.uuid ];
  5987. }
  5988. const output = {
  5989. metadata: {
  5990. version: 4.7,
  5991. type: 'Texture',
  5992. generator: 'Texture.toJSON'
  5993. },
  5994. uuid: this.uuid,
  5995. name: this.name,
  5996. image: this.source.toJSON( meta ).uuid,
  5997. mapping: this.mapping,
  5998. channel: this.channel,
  5999. repeat: [ this.repeat.x, this.repeat.y ],
  6000. offset: [ this.offset.x, this.offset.y ],
  6001. center: [ this.center.x, this.center.y ],
  6002. rotation: this.rotation,
  6003. wrap: [ this.wrapS, this.wrapT ],
  6004. format: this.format,
  6005. internalFormat: this.internalFormat,
  6006. type: this.type,
  6007. colorSpace: this.colorSpace,
  6008. minFilter: this.minFilter,
  6009. magFilter: this.magFilter,
  6010. anisotropy: this.anisotropy,
  6011. flipY: this.flipY,
  6012. generateMipmaps: this.generateMipmaps,
  6013. premultiplyAlpha: this.premultiplyAlpha,
  6014. unpackAlignment: this.unpackAlignment
  6015. };
  6016. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6017. if ( ! isRootObject ) {
  6018. meta.textures[ this.uuid ] = output;
  6019. }
  6020. return output;
  6021. }
  6022. /**
  6023. * Frees the GPU-related resources allocated by this instance. Call this
  6024. * method whenever this instance is no longer used in your app.
  6025. *
  6026. * @fires Texture#dispose
  6027. */
  6028. dispose() {
  6029. /**
  6030. * Fires when the texture has been disposed of.
  6031. *
  6032. * @event Texture#dispose
  6033. * @type {Object}
  6034. */
  6035. this.dispatchEvent( { type: 'dispose' } );
  6036. }
  6037. /**
  6038. * Transforms the given uv vector with the textures uv transformation matrix.
  6039. *
  6040. * @param {Vector2} uv - The uv vector.
  6041. * @return {Vector2} The transformed uv vector.
  6042. */
  6043. transformUv( uv ) {
  6044. if ( this.mapping !== UVMapping ) return uv;
  6045. uv.applyMatrix3( this.matrix );
  6046. if ( uv.x < 0 || uv.x > 1 ) {
  6047. switch ( this.wrapS ) {
  6048. case RepeatWrapping:
  6049. uv.x = uv.x - Math.floor( uv.x );
  6050. break;
  6051. case ClampToEdgeWrapping:
  6052. uv.x = uv.x < 0 ? 0 : 1;
  6053. break;
  6054. case MirroredRepeatWrapping:
  6055. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6056. uv.x = Math.ceil( uv.x ) - uv.x;
  6057. } else {
  6058. uv.x = uv.x - Math.floor( uv.x );
  6059. }
  6060. break;
  6061. }
  6062. }
  6063. if ( uv.y < 0 || uv.y > 1 ) {
  6064. switch ( this.wrapT ) {
  6065. case RepeatWrapping:
  6066. uv.y = uv.y - Math.floor( uv.y );
  6067. break;
  6068. case ClampToEdgeWrapping:
  6069. uv.y = uv.y < 0 ? 0 : 1;
  6070. break;
  6071. case MirroredRepeatWrapping:
  6072. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6073. uv.y = Math.ceil( uv.y ) - uv.y;
  6074. } else {
  6075. uv.y = uv.y - Math.floor( uv.y );
  6076. }
  6077. break;
  6078. }
  6079. }
  6080. if ( this.flipY ) {
  6081. uv.y = 1 - uv.y;
  6082. }
  6083. return uv;
  6084. }
  6085. /**
  6086. * Setting this property to `true` indicates the engine the texture
  6087. * must be updated in the next render. This triggers a texture upload
  6088. * to the GPU and ensures correct texture parameter configuration.
  6089. *
  6090. * @type {boolean}
  6091. * @default false
  6092. * @param {boolean} value
  6093. */
  6094. set needsUpdate( value ) {
  6095. if ( value === true ) {
  6096. this.version ++;
  6097. this.source.needsUpdate = true;
  6098. }
  6099. }
  6100. /**
  6101. * Setting this property to `true` indicates the engine the PMREM
  6102. * must be regenerated.
  6103. *
  6104. * @type {boolean}
  6105. * @default false
  6106. * @param {boolean} value
  6107. */
  6108. set needsPMREMUpdate( value ) {
  6109. if ( value === true ) {
  6110. this.pmremVersion ++;
  6111. }
  6112. }
  6113. }
  6114. /**
  6115. * The default image for all textures.
  6116. *
  6117. * @static
  6118. * @type {?Image}
  6119. * @default null
  6120. */
  6121. Texture.DEFAULT_IMAGE = null;
  6122. /**
  6123. * The default mapping for all textures.
  6124. *
  6125. * @static
  6126. * @type {number}
  6127. * @default UVMapping
  6128. */
  6129. Texture.DEFAULT_MAPPING = UVMapping;
  6130. /**
  6131. * The default anisotropy value for all textures.
  6132. *
  6133. * @static
  6134. * @type {number}
  6135. * @default 1
  6136. */
  6137. Texture.DEFAULT_ANISOTROPY = 1;
  6138. /**
  6139. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6140. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6141. *
  6142. * - A point in 4D space.
  6143. * - A direction and length in 4D space. In three.js the length will
  6144. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6145. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6146. * - Any arbitrary ordered quadruplet of numbers.
  6147. *
  6148. * There are other things a 4D vector can be used to represent, however these
  6149. * are the most common uses in *three.js*.
  6150. *
  6151. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6152. * the corresponding order.
  6153. * ```js
  6154. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6155. *
  6156. * //no arguments; will be initialised to (0, 0, 0, 1)
  6157. * const b = new THREE.Vector4( );
  6158. *
  6159. * const d = a.dot( b );
  6160. * ```
  6161. */
  6162. class Vector4 {
  6163. /**
  6164. * Constructs a new 4D vector.
  6165. *
  6166. * @param {number} [x=0] - The x value of this vector.
  6167. * @param {number} [y=0] - The y value of this vector.
  6168. * @param {number} [z=0] - The z value of this vector.
  6169. * @param {number} [w=1] - The w value of this vector.
  6170. */
  6171. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6172. /**
  6173. * This flag can be used for type testing.
  6174. *
  6175. * @type {boolean}
  6176. * @readonly
  6177. * @default true
  6178. */
  6179. Vector4.prototype.isVector4 = true;
  6180. /**
  6181. * The x value of this vector.
  6182. *
  6183. * @type {number}
  6184. */
  6185. this.x = x;
  6186. /**
  6187. * The y value of this vector.
  6188. *
  6189. * @type {number}
  6190. */
  6191. this.y = y;
  6192. /**
  6193. * The z value of this vector.
  6194. *
  6195. * @type {number}
  6196. */
  6197. this.z = z;
  6198. /**
  6199. * The w value of this vector.
  6200. *
  6201. * @type {number}
  6202. */
  6203. this.w = w;
  6204. }
  6205. /**
  6206. * Alias for {@link Vector4#z}.
  6207. *
  6208. * @type {number}
  6209. */
  6210. get width() {
  6211. return this.z;
  6212. }
  6213. set width( value ) {
  6214. this.z = value;
  6215. }
  6216. /**
  6217. * Alias for {@link Vector4#w}.
  6218. *
  6219. * @type {number}
  6220. */
  6221. get height() {
  6222. return this.w;
  6223. }
  6224. set height( value ) {
  6225. this.w = value;
  6226. }
  6227. /**
  6228. * Sets the vector components.
  6229. *
  6230. * @param {number} x - The value of the x component.
  6231. * @param {number} y - The value of the y component.
  6232. * @param {number} z - The value of the z component.
  6233. * @param {number} w - The value of the w component.
  6234. * @return {Vector4} A reference to this vector.
  6235. */
  6236. set( x, y, z, w ) {
  6237. this.x = x;
  6238. this.y = y;
  6239. this.z = z;
  6240. this.w = w;
  6241. return this;
  6242. }
  6243. /**
  6244. * Sets the vector components to the same value.
  6245. *
  6246. * @param {number} scalar - The value to set for all vector components.
  6247. * @return {Vector4} A reference to this vector.
  6248. */
  6249. setScalar( scalar ) {
  6250. this.x = scalar;
  6251. this.y = scalar;
  6252. this.z = scalar;
  6253. this.w = scalar;
  6254. return this;
  6255. }
  6256. /**
  6257. * Sets the vector's x component to the given value
  6258. *
  6259. * @param {number} x - The value to set.
  6260. * @return {Vector4} A reference to this vector.
  6261. */
  6262. setX( x ) {
  6263. this.x = x;
  6264. return this;
  6265. }
  6266. /**
  6267. * Sets the vector's y component to the given value
  6268. *
  6269. * @param {number} y - The value to set.
  6270. * @return {Vector4} A reference to this vector.
  6271. */
  6272. setY( y ) {
  6273. this.y = y;
  6274. return this;
  6275. }
  6276. /**
  6277. * Sets the vector's z component to the given value
  6278. *
  6279. * @param {number} z - The value to set.
  6280. * @return {Vector4} A reference to this vector.
  6281. */
  6282. setZ( z ) {
  6283. this.z = z;
  6284. return this;
  6285. }
  6286. /**
  6287. * Sets the vector's w component to the given value
  6288. *
  6289. * @param {number} w - The value to set.
  6290. * @return {Vector4} A reference to this vector.
  6291. */
  6292. setW( w ) {
  6293. this.w = w;
  6294. return this;
  6295. }
  6296. /**
  6297. * Allows to set a vector component with an index.
  6298. *
  6299. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6300. * `2` equals to z, `3` equals to w.
  6301. * @param {number} value - The value to set.
  6302. * @return {Vector4} A reference to this vector.
  6303. */
  6304. setComponent( index, value ) {
  6305. switch ( index ) {
  6306. case 0: this.x = value; break;
  6307. case 1: this.y = value; break;
  6308. case 2: this.z = value; break;
  6309. case 3: this.w = value; break;
  6310. default: throw new Error( 'index is out of range: ' + index );
  6311. }
  6312. return this;
  6313. }
  6314. /**
  6315. * Returns the value of the vector component which matches the given index.
  6316. *
  6317. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6318. * `2` equals to z, `3` equals to w.
  6319. * @return {number} A vector component value.
  6320. */
  6321. getComponent( index ) {
  6322. switch ( index ) {
  6323. case 0: return this.x;
  6324. case 1: return this.y;
  6325. case 2: return this.z;
  6326. case 3: return this.w;
  6327. default: throw new Error( 'index is out of range: ' + index );
  6328. }
  6329. }
  6330. /**
  6331. * Returns a new vector with copied values from this instance.
  6332. *
  6333. * @return {Vector4} A clone of this instance.
  6334. */
  6335. clone() {
  6336. return new this.constructor( this.x, this.y, this.z, this.w );
  6337. }
  6338. /**
  6339. * Copies the values of the given vector to this instance.
  6340. *
  6341. * @param {Vector3|Vector4} v - The vector to copy.
  6342. * @return {Vector4} A reference to this vector.
  6343. */
  6344. copy( v ) {
  6345. this.x = v.x;
  6346. this.y = v.y;
  6347. this.z = v.z;
  6348. this.w = ( v.w !== undefined ) ? v.w : 1;
  6349. return this;
  6350. }
  6351. /**
  6352. * Adds the given vector to this instance.
  6353. *
  6354. * @param {Vector4} v - The vector to add.
  6355. * @return {Vector4} A reference to this vector.
  6356. */
  6357. add( v ) {
  6358. this.x += v.x;
  6359. this.y += v.y;
  6360. this.z += v.z;
  6361. this.w += v.w;
  6362. return this;
  6363. }
  6364. /**
  6365. * Adds the given scalar value to all components of this instance.
  6366. *
  6367. * @param {number} s - The scalar to add.
  6368. * @return {Vector4} A reference to this vector.
  6369. */
  6370. addScalar( s ) {
  6371. this.x += s;
  6372. this.y += s;
  6373. this.z += s;
  6374. this.w += s;
  6375. return this;
  6376. }
  6377. /**
  6378. * Adds the given vectors and stores the result in this instance.
  6379. *
  6380. * @param {Vector4} a - The first vector.
  6381. * @param {Vector4} b - The second vector.
  6382. * @return {Vector4} A reference to this vector.
  6383. */
  6384. addVectors( a, b ) {
  6385. this.x = a.x + b.x;
  6386. this.y = a.y + b.y;
  6387. this.z = a.z + b.z;
  6388. this.w = a.w + b.w;
  6389. return this;
  6390. }
  6391. /**
  6392. * Adds the given vector scaled by the given factor to this instance.
  6393. *
  6394. * @param {Vector4} v - The vector.
  6395. * @param {number} s - The factor that scales `v`.
  6396. * @return {Vector4} A reference to this vector.
  6397. */
  6398. addScaledVector( v, s ) {
  6399. this.x += v.x * s;
  6400. this.y += v.y * s;
  6401. this.z += v.z * s;
  6402. this.w += v.w * s;
  6403. return this;
  6404. }
  6405. /**
  6406. * Subtracts the given vector from this instance.
  6407. *
  6408. * @param {Vector4} v - The vector to subtract.
  6409. * @return {Vector4} A reference to this vector.
  6410. */
  6411. sub( v ) {
  6412. this.x -= v.x;
  6413. this.y -= v.y;
  6414. this.z -= v.z;
  6415. this.w -= v.w;
  6416. return this;
  6417. }
  6418. /**
  6419. * Subtracts the given scalar value from all components of this instance.
  6420. *
  6421. * @param {number} s - The scalar to subtract.
  6422. * @return {Vector4} A reference to this vector.
  6423. */
  6424. subScalar( s ) {
  6425. this.x -= s;
  6426. this.y -= s;
  6427. this.z -= s;
  6428. this.w -= s;
  6429. return this;
  6430. }
  6431. /**
  6432. * Subtracts the given vectors and stores the result in this instance.
  6433. *
  6434. * @param {Vector4} a - The first vector.
  6435. * @param {Vector4} b - The second vector.
  6436. * @return {Vector4} A reference to this vector.
  6437. */
  6438. subVectors( a, b ) {
  6439. this.x = a.x - b.x;
  6440. this.y = a.y - b.y;
  6441. this.z = a.z - b.z;
  6442. this.w = a.w - b.w;
  6443. return this;
  6444. }
  6445. /**
  6446. * Multiplies the given vector with this instance.
  6447. *
  6448. * @param {Vector4} v - The vector to multiply.
  6449. * @return {Vector4} A reference to this vector.
  6450. */
  6451. multiply( v ) {
  6452. this.x *= v.x;
  6453. this.y *= v.y;
  6454. this.z *= v.z;
  6455. this.w *= v.w;
  6456. return this;
  6457. }
  6458. /**
  6459. * Multiplies the given scalar value with all components of this instance.
  6460. *
  6461. * @param {number} scalar - The scalar to multiply.
  6462. * @return {Vector4} A reference to this vector.
  6463. */
  6464. multiplyScalar( scalar ) {
  6465. this.x *= scalar;
  6466. this.y *= scalar;
  6467. this.z *= scalar;
  6468. this.w *= scalar;
  6469. return this;
  6470. }
  6471. /**
  6472. * Multiplies this vector with the given 4x4 matrix.
  6473. *
  6474. * @param {Matrix4} m - The 4x4 matrix.
  6475. * @return {Vector4} A reference to this vector.
  6476. */
  6477. applyMatrix4( m ) {
  6478. const x = this.x, y = this.y, z = this.z, w = this.w;
  6479. const e = m.elements;
  6480. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6481. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6482. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6483. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6484. return this;
  6485. }
  6486. /**
  6487. * Divides this instance by the given vector.
  6488. *
  6489. * @param {Vector4} v - The vector to divide.
  6490. * @return {Vector4} A reference to this vector.
  6491. */
  6492. divide( v ) {
  6493. this.x /= v.x;
  6494. this.y /= v.y;
  6495. this.z /= v.z;
  6496. this.w /= v.w;
  6497. return this;
  6498. }
  6499. /**
  6500. * Divides this vector by the given scalar.
  6501. *
  6502. * @param {number} scalar - The scalar to divide.
  6503. * @return {Vector4} A reference to this vector.
  6504. */
  6505. divideScalar( scalar ) {
  6506. return this.multiplyScalar( 1 / scalar );
  6507. }
  6508. /**
  6509. * Sets the x, y and z components of this
  6510. * vector to the quaternion's axis and w to the angle.
  6511. *
  6512. * @param {Quaternion} q - The Quaternion to set.
  6513. * @return {Vector4} A reference to this vector.
  6514. */
  6515. setAxisAngleFromQuaternion( q ) {
  6516. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6517. // q is assumed to be normalized
  6518. this.w = 2 * Math.acos( q.w );
  6519. const s = Math.sqrt( 1 - q.w * q.w );
  6520. if ( s < 0.0001 ) {
  6521. this.x = 1;
  6522. this.y = 0;
  6523. this.z = 0;
  6524. } else {
  6525. this.x = q.x / s;
  6526. this.y = q.y / s;
  6527. this.z = q.z / s;
  6528. }
  6529. return this;
  6530. }
  6531. /**
  6532. * Sets the x, y and z components of this
  6533. * vector to the axis of rotation and w to the angle.
  6534. *
  6535. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6536. * @return {Vector4} A reference to this vector.
  6537. */
  6538. setAxisAngleFromRotationMatrix( m ) {
  6539. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6540. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6541. let angle, x, y, z; // variables for result
  6542. const epsilon = 0.01, // margin to allow for rounding errors
  6543. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6544. te = m.elements,
  6545. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6546. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6547. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6548. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6549. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6550. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6551. // singularity found
  6552. // first check for identity matrix which must have +1 for all terms
  6553. // in leading diagonal and zero in other terms
  6554. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6555. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6556. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6557. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6558. // this singularity is identity matrix so angle = 0
  6559. this.set( 1, 0, 0, 0 );
  6560. return this; // zero angle, arbitrary axis
  6561. }
  6562. // otherwise this singularity is angle = 180
  6563. angle = Math.PI;
  6564. const xx = ( m11 + 1 ) / 2;
  6565. const yy = ( m22 + 1 ) / 2;
  6566. const zz = ( m33 + 1 ) / 2;
  6567. const xy = ( m12 + m21 ) / 4;
  6568. const xz = ( m13 + m31 ) / 4;
  6569. const yz = ( m23 + m32 ) / 4;
  6570. if ( ( xx > yy ) && ( xx > zz ) ) {
  6571. // m11 is the largest diagonal term
  6572. if ( xx < epsilon ) {
  6573. x = 0;
  6574. y = 0.707106781;
  6575. z = 0.707106781;
  6576. } else {
  6577. x = Math.sqrt( xx );
  6578. y = xy / x;
  6579. z = xz / x;
  6580. }
  6581. } else if ( yy > zz ) {
  6582. // m22 is the largest diagonal term
  6583. if ( yy < epsilon ) {
  6584. x = 0.707106781;
  6585. y = 0;
  6586. z = 0.707106781;
  6587. } else {
  6588. y = Math.sqrt( yy );
  6589. x = xy / y;
  6590. z = yz / y;
  6591. }
  6592. } else {
  6593. // m33 is the largest diagonal term so base result on this
  6594. if ( zz < epsilon ) {
  6595. x = 0.707106781;
  6596. y = 0.707106781;
  6597. z = 0;
  6598. } else {
  6599. z = Math.sqrt( zz );
  6600. x = xz / z;
  6601. y = yz / z;
  6602. }
  6603. }
  6604. this.set( x, y, z, angle );
  6605. return this; // return 180 deg rotation
  6606. }
  6607. // as we have reached here there are no singularities so we can handle normally
  6608. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6609. ( m13 - m31 ) * ( m13 - m31 ) +
  6610. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6611. if ( Math.abs( s ) < 0.001 ) s = 1;
  6612. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6613. // caught by singularity test above, but I've left it in just in case
  6614. this.x = ( m32 - m23 ) / s;
  6615. this.y = ( m13 - m31 ) / s;
  6616. this.z = ( m21 - m12 ) / s;
  6617. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6618. return this;
  6619. }
  6620. /**
  6621. * Sets the vector components to the position elements of the
  6622. * given transformation matrix.
  6623. *
  6624. * @param {Matrix4} m - The 4x4 matrix.
  6625. * @return {Vector4} A reference to this vector.
  6626. */
  6627. setFromMatrixPosition( m ) {
  6628. const e = m.elements;
  6629. this.x = e[ 12 ];
  6630. this.y = e[ 13 ];
  6631. this.z = e[ 14 ];
  6632. this.w = e[ 15 ];
  6633. return this;
  6634. }
  6635. /**
  6636. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6637. * value, replace that value with the corresponding min value.
  6638. *
  6639. * @param {Vector4} v - The vector.
  6640. * @return {Vector4} A reference to this vector.
  6641. */
  6642. min( v ) {
  6643. this.x = Math.min( this.x, v.x );
  6644. this.y = Math.min( this.y, v.y );
  6645. this.z = Math.min( this.z, v.z );
  6646. this.w = Math.min( this.w, v.w );
  6647. return this;
  6648. }
  6649. /**
  6650. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6651. * value, replace that value with the corresponding max value.
  6652. *
  6653. * @param {Vector4} v - The vector.
  6654. * @return {Vector4} A reference to this vector.
  6655. */
  6656. max( v ) {
  6657. this.x = Math.max( this.x, v.x );
  6658. this.y = Math.max( this.y, v.y );
  6659. this.z = Math.max( this.z, v.z );
  6660. this.w = Math.max( this.w, v.w );
  6661. return this;
  6662. }
  6663. /**
  6664. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6665. * value, it is replaced by the corresponding value.
  6666. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6667. * it is replaced by the corresponding value.
  6668. *
  6669. * @param {Vector4} min - The minimum x, y and z values.
  6670. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6671. * @return {Vector4} A reference to this vector.
  6672. */
  6673. clamp( min, max ) {
  6674. // assumes min < max, componentwise
  6675. this.x = clamp( this.x, min.x, max.x );
  6676. this.y = clamp( this.y, min.y, max.y );
  6677. this.z = clamp( this.z, min.z, max.z );
  6678. this.w = clamp( this.w, min.w, max.w );
  6679. return this;
  6680. }
  6681. /**
  6682. * If this vector's x, y, z or w values are greater than the max value, they are
  6683. * replaced by the max value.
  6684. * If this vector's x, y, z or w values are less than the min value, they are
  6685. * replaced by the min value.
  6686. *
  6687. * @param {number} minVal - The minimum value the components will be clamped to.
  6688. * @param {number} maxVal - The maximum value the components will be clamped to.
  6689. * @return {Vector4} A reference to this vector.
  6690. */
  6691. clampScalar( minVal, maxVal ) {
  6692. this.x = clamp( this.x, minVal, maxVal );
  6693. this.y = clamp( this.y, minVal, maxVal );
  6694. this.z = clamp( this.z, minVal, maxVal );
  6695. this.w = clamp( this.w, minVal, maxVal );
  6696. return this;
  6697. }
  6698. /**
  6699. * If this vector's length is greater than the max value, it is replaced by
  6700. * the max value.
  6701. * If this vector's length is less than the min value, it is replaced by the
  6702. * min value.
  6703. *
  6704. * @param {number} min - The minimum value the vector length will be clamped to.
  6705. * @param {number} max - The maximum value the vector length will be clamped to.
  6706. * @return {Vector4} A reference to this vector.
  6707. */
  6708. clampLength( min, max ) {
  6709. const length = this.length();
  6710. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6711. }
  6712. /**
  6713. * The components of this vector are rounded down to the nearest integer value.
  6714. *
  6715. * @return {Vector4} A reference to this vector.
  6716. */
  6717. floor() {
  6718. this.x = Math.floor( this.x );
  6719. this.y = Math.floor( this.y );
  6720. this.z = Math.floor( this.z );
  6721. this.w = Math.floor( this.w );
  6722. return this;
  6723. }
  6724. /**
  6725. * The components of this vector are rounded up to the nearest integer value.
  6726. *
  6727. * @return {Vector4} A reference to this vector.
  6728. */
  6729. ceil() {
  6730. this.x = Math.ceil( this.x );
  6731. this.y = Math.ceil( this.y );
  6732. this.z = Math.ceil( this.z );
  6733. this.w = Math.ceil( this.w );
  6734. return this;
  6735. }
  6736. /**
  6737. * The components of this vector are rounded to the nearest integer value
  6738. *
  6739. * @return {Vector4} A reference to this vector.
  6740. */
  6741. round() {
  6742. this.x = Math.round( this.x );
  6743. this.y = Math.round( this.y );
  6744. this.z = Math.round( this.z );
  6745. this.w = Math.round( this.w );
  6746. return this;
  6747. }
  6748. /**
  6749. * The components of this vector are rounded towards zero (up if negative,
  6750. * down if positive) to an integer value.
  6751. *
  6752. * @return {Vector4} A reference to this vector.
  6753. */
  6754. roundToZero() {
  6755. this.x = Math.trunc( this.x );
  6756. this.y = Math.trunc( this.y );
  6757. this.z = Math.trunc( this.z );
  6758. this.w = Math.trunc( this.w );
  6759. return this;
  6760. }
  6761. /**
  6762. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6763. *
  6764. * @return {Vector4} A reference to this vector.
  6765. */
  6766. negate() {
  6767. this.x = - this.x;
  6768. this.y = - this.y;
  6769. this.z = - this.z;
  6770. this.w = - this.w;
  6771. return this;
  6772. }
  6773. /**
  6774. * Calculates the dot product of the given vector with this instance.
  6775. *
  6776. * @param {Vector4} v - The vector to compute the dot product with.
  6777. * @return {number} The result of the dot product.
  6778. */
  6779. dot( v ) {
  6780. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6781. }
  6782. /**
  6783. * Computes the square of the Euclidean length (straight-line length) from
  6784. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6785. * compare the length squared instead as it is slightly more efficient to calculate.
  6786. *
  6787. * @return {number} The square length of this vector.
  6788. */
  6789. lengthSq() {
  6790. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6791. }
  6792. /**
  6793. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6794. *
  6795. * @return {number} The length of this vector.
  6796. */
  6797. length() {
  6798. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6799. }
  6800. /**
  6801. * Computes the Manhattan length of this vector.
  6802. *
  6803. * @return {number} The length of this vector.
  6804. */
  6805. manhattanLength() {
  6806. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6807. }
  6808. /**
  6809. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6810. * with the same direction as this one, but with a vector length of `1`.
  6811. *
  6812. * @return {Vector4} A reference to this vector.
  6813. */
  6814. normalize() {
  6815. return this.divideScalar( this.length() || 1 );
  6816. }
  6817. /**
  6818. * Sets this vector to a vector with the same direction as this one, but
  6819. * with the specified length.
  6820. *
  6821. * @param {number} length - The new length of this vector.
  6822. * @return {Vector4} A reference to this vector.
  6823. */
  6824. setLength( length ) {
  6825. return this.normalize().multiplyScalar( length );
  6826. }
  6827. /**
  6828. * Linearly interpolates between the given vector and this instance, where
  6829. * alpha is the percent distance along the line - alpha = 0 will be this
  6830. * vector, and alpha = 1 will be the given one.
  6831. *
  6832. * @param {Vector4} v - The vector to interpolate towards.
  6833. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6834. * @return {Vector4} A reference to this vector.
  6835. */
  6836. lerp( v, alpha ) {
  6837. this.x += ( v.x - this.x ) * alpha;
  6838. this.y += ( v.y - this.y ) * alpha;
  6839. this.z += ( v.z - this.z ) * alpha;
  6840. this.w += ( v.w - this.w ) * alpha;
  6841. return this;
  6842. }
  6843. /**
  6844. * Linearly interpolates between the given vectors, where alpha is the percent
  6845. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6846. * be the second one. The result is stored in this instance.
  6847. *
  6848. * @param {Vector4} v1 - The first vector.
  6849. * @param {Vector4} v2 - The second vector.
  6850. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6851. * @return {Vector4} A reference to this vector.
  6852. */
  6853. lerpVectors( v1, v2, alpha ) {
  6854. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6855. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6856. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6857. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6858. return this;
  6859. }
  6860. /**
  6861. * Returns `true` if this vector is equal with the given one.
  6862. *
  6863. * @param {Vector4} v - The vector to test for equality.
  6864. * @return {boolean} Whether this vector is equal with the given one.
  6865. */
  6866. equals( v ) {
  6867. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6868. }
  6869. /**
  6870. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6871. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6872. *
  6873. * @param {Array<number>} array - An array holding the vector component values.
  6874. * @param {number} [offset=0] - The offset into the array.
  6875. * @return {Vector4} A reference to this vector.
  6876. */
  6877. fromArray( array, offset = 0 ) {
  6878. this.x = array[ offset ];
  6879. this.y = array[ offset + 1 ];
  6880. this.z = array[ offset + 2 ];
  6881. this.w = array[ offset + 3 ];
  6882. return this;
  6883. }
  6884. /**
  6885. * Writes the components of this vector to the given array. If no array is provided,
  6886. * the method returns a new instance.
  6887. *
  6888. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6889. * @param {number} [offset=0] - Index of the first element in the array.
  6890. * @return {Array<number>} The vector components.
  6891. */
  6892. toArray( array = [], offset = 0 ) {
  6893. array[ offset ] = this.x;
  6894. array[ offset + 1 ] = this.y;
  6895. array[ offset + 2 ] = this.z;
  6896. array[ offset + 3 ] = this.w;
  6897. return array;
  6898. }
  6899. /**
  6900. * Sets the components of this vector from the given buffer attribute.
  6901. *
  6902. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6903. * @param {number} index - The index into the attribute.
  6904. * @return {Vector4} A reference to this vector.
  6905. */
  6906. fromBufferAttribute( attribute, index ) {
  6907. this.x = attribute.getX( index );
  6908. this.y = attribute.getY( index );
  6909. this.z = attribute.getZ( index );
  6910. this.w = attribute.getW( index );
  6911. return this;
  6912. }
  6913. /**
  6914. * Sets each component of this vector to a pseudo-random value between `0` and
  6915. * `1`, excluding `1`.
  6916. *
  6917. * @return {Vector4} A reference to this vector.
  6918. */
  6919. random() {
  6920. this.x = Math.random();
  6921. this.y = Math.random();
  6922. this.z = Math.random();
  6923. this.w = Math.random();
  6924. return this;
  6925. }
  6926. *[ Symbol.iterator ]() {
  6927. yield this.x;
  6928. yield this.y;
  6929. yield this.z;
  6930. yield this.w;
  6931. }
  6932. }
  6933. /**
  6934. * A render target is a buffer where the video card draws pixels for a scene
  6935. * that is being rendered in the background. It is used in different effects,
  6936. * such as applying postprocessing to a rendered image before displaying it
  6937. * on the screen.
  6938. *
  6939. * @augments EventDispatcher
  6940. */
  6941. class RenderTarget extends EventDispatcher {
  6942. /**
  6943. * Render target options.
  6944. *
  6945. * @typedef {Object} RenderTarget~Options
  6946. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6947. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6948. * @property {number} [minFilter=LinearFilter] - The min filter.
  6949. * @property {number} [format=RGBAFormat] - The texture format.
  6950. * @property {number} [type=UnsignedByteType] - The texture type.
  6951. * @property {?string} [internalFormat=null] - The texture's internal format.
  6952. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6953. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6954. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6955. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6956. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6957. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6958. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6959. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6960. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6961. * @property {number} [samples=0] - The MSAA samples count.
  6962. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6963. * @property {number} [depth=1] - The texture depth.
  6964. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6965. */
  6966. /**
  6967. * Constructs a new render target.
  6968. *
  6969. * @param {number} [width=1] - The width of the render target.
  6970. * @param {number} [height=1] - The height of the render target.
  6971. * @param {RenderTarget~Options} [options] - The configuration object.
  6972. */
  6973. constructor( width = 1, height = 1, options = {} ) {
  6974. super();
  6975. options = Object.assign( {
  6976. generateMipmaps: false,
  6977. internalFormat: null,
  6978. minFilter: LinearFilter,
  6979. depthBuffer: true,
  6980. stencilBuffer: false,
  6981. resolveDepthBuffer: true,
  6982. resolveStencilBuffer: true,
  6983. depthTexture: null,
  6984. samples: 0,
  6985. count: 1,
  6986. depth: 1,
  6987. multiview: false
  6988. }, options );
  6989. /**
  6990. * This flag can be used for type testing.
  6991. *
  6992. * @type {boolean}
  6993. * @readonly
  6994. * @default true
  6995. */
  6996. this.isRenderTarget = true;
  6997. /**
  6998. * The width of the render target.
  6999. *
  7000. * @type {number}
  7001. * @default 1
  7002. */
  7003. this.width = width;
  7004. /**
  7005. * The height of the render target.
  7006. *
  7007. * @type {number}
  7008. * @default 1
  7009. */
  7010. this.height = height;
  7011. /**
  7012. * The depth of the render target.
  7013. *
  7014. * @type {number}
  7015. * @default 1
  7016. */
  7017. this.depth = options.depth;
  7018. /**
  7019. * A rectangular area inside the render target's viewport. Fragments that are
  7020. * outside the area will be discarded.
  7021. *
  7022. * @type {Vector4}
  7023. * @default (0,0,width,height)
  7024. */
  7025. this.scissor = new Vector4( 0, 0, width, height );
  7026. /**
  7027. * Indicates whether the scissor test should be enabled when rendering into
  7028. * this render target or not.
  7029. *
  7030. * @type {boolean}
  7031. * @default false
  7032. */
  7033. this.scissorTest = false;
  7034. /**
  7035. * A rectangular area representing the render target's viewport.
  7036. *
  7037. * @type {Vector4}
  7038. * @default (0,0,width,height)
  7039. */
  7040. this.viewport = new Vector4( 0, 0, width, height );
  7041. const image = { width: width, height: height, depth: options.depth };
  7042. const texture = new Texture( image );
  7043. /**
  7044. * An array of textures. Each color attachment is represented as a separate texture.
  7045. * Has at least a single entry for the default color attachment.
  7046. *
  7047. * @type {Array<Texture>}
  7048. */
  7049. this.textures = [];
  7050. const count = options.count;
  7051. for ( let i = 0; i < count; i ++ ) {
  7052. this.textures[ i ] = texture.clone();
  7053. this.textures[ i ].isRenderTargetTexture = true;
  7054. this.textures[ i ].renderTarget = this;
  7055. }
  7056. this._setTextureOptions( options );
  7057. /**
  7058. * Whether to allocate a depth buffer or not.
  7059. *
  7060. * @type {boolean}
  7061. * @default true
  7062. */
  7063. this.depthBuffer = options.depthBuffer;
  7064. /**
  7065. * Whether to allocate a stencil buffer or not.
  7066. *
  7067. * @type {boolean}
  7068. * @default false
  7069. */
  7070. this.stencilBuffer = options.stencilBuffer;
  7071. /**
  7072. * Whether to resolve the depth buffer or not.
  7073. *
  7074. * @type {boolean}
  7075. * @default true
  7076. */
  7077. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7078. /**
  7079. * Whether to resolve the stencil buffer or not.
  7080. *
  7081. * @type {boolean}
  7082. * @default true
  7083. */
  7084. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7085. this._depthTexture = null;
  7086. this.depthTexture = options.depthTexture;
  7087. /**
  7088. * The number of MSAA samples.
  7089. *
  7090. * A value of `0` disables MSAA.
  7091. *
  7092. * @type {number}
  7093. * @default 0
  7094. */
  7095. this.samples = options.samples;
  7096. /**
  7097. * Whether to this target is used in multiview rendering.
  7098. *
  7099. * @type {boolean}
  7100. * @default false
  7101. */
  7102. this.multiview = options.multiview;
  7103. }
  7104. _setTextureOptions( options = {} ) {
  7105. const values = {
  7106. minFilter: LinearFilter,
  7107. generateMipmaps: false,
  7108. flipY: false,
  7109. internalFormat: null
  7110. };
  7111. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7112. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7113. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7114. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7115. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7116. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7117. if ( options.format !== undefined ) values.format = options.format;
  7118. if ( options.type !== undefined ) values.type = options.type;
  7119. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7120. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7121. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7122. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7123. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7124. for ( let i = 0; i < this.textures.length; i ++ ) {
  7125. const texture = this.textures[ i ];
  7126. texture.setValues( values );
  7127. }
  7128. }
  7129. /**
  7130. * The texture representing the default color attachment.
  7131. *
  7132. * @type {Texture}
  7133. */
  7134. get texture() {
  7135. return this.textures[ 0 ];
  7136. }
  7137. set texture( value ) {
  7138. this.textures[ 0 ] = value;
  7139. }
  7140. set depthTexture( current ) {
  7141. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7142. if ( current !== null ) current.renderTarget = this;
  7143. this._depthTexture = current;
  7144. }
  7145. /**
  7146. * Instead of saving the depth in a renderbuffer, a texture
  7147. * can be used instead which is useful for further processing
  7148. * e.g. in context of post-processing.
  7149. *
  7150. * @type {?DepthTexture}
  7151. * @default null
  7152. */
  7153. get depthTexture() {
  7154. return this._depthTexture;
  7155. }
  7156. /**
  7157. * Sets the size of this render target.
  7158. *
  7159. * @param {number} width - The width.
  7160. * @param {number} height - The height.
  7161. * @param {number} [depth=1] - The depth.
  7162. */
  7163. setSize( width, height, depth = 1 ) {
  7164. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7165. this.width = width;
  7166. this.height = height;
  7167. this.depth = depth;
  7168. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7169. this.textures[ i ].image.width = width;
  7170. this.textures[ i ].image.height = height;
  7171. this.textures[ i ].image.depth = depth;
  7172. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7173. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7174. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7175. // both are evaluated on each call?
  7176. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7177. }
  7178. }
  7179. this.dispose();
  7180. }
  7181. this.viewport.set( 0, 0, width, height );
  7182. this.scissor.set( 0, 0, width, height );
  7183. }
  7184. /**
  7185. * Returns a new render target with copied values from this instance.
  7186. *
  7187. * @return {RenderTarget} A clone of this instance.
  7188. */
  7189. clone() {
  7190. return new this.constructor().copy( this );
  7191. }
  7192. /**
  7193. * Copies the settings of the given render target. This is a structural copy so
  7194. * no resources are shared between render targets after the copy. That includes
  7195. * all MRT textures and the depth texture.
  7196. *
  7197. * @param {RenderTarget} source - The render target to copy.
  7198. * @return {RenderTarget} A reference to this instance.
  7199. */
  7200. copy( source ) {
  7201. this.width = source.width;
  7202. this.height = source.height;
  7203. this.depth = source.depth;
  7204. this.scissor.copy( source.scissor );
  7205. this.scissorTest = source.scissorTest;
  7206. this.viewport.copy( source.viewport );
  7207. this.textures.length = 0;
  7208. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7209. this.textures[ i ] = source.textures[ i ].clone();
  7210. this.textures[ i ].isRenderTargetTexture = true;
  7211. this.textures[ i ].renderTarget = this;
  7212. // ensure image object is not shared, see #20328
  7213. const image = Object.assign( {}, source.textures[ i ].image );
  7214. this.textures[ i ].source = new Source( image );
  7215. }
  7216. this.depthBuffer = source.depthBuffer;
  7217. this.stencilBuffer = source.stencilBuffer;
  7218. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7219. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7220. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7221. this.samples = source.samples;
  7222. return this;
  7223. }
  7224. /**
  7225. * Frees the GPU-related resources allocated by this instance. Call this
  7226. * method whenever this instance is no longer used in your app.
  7227. *
  7228. * @fires RenderTarget#dispose
  7229. */
  7230. dispose() {
  7231. this.dispatchEvent( { type: 'dispose' } );
  7232. }
  7233. }
  7234. /**
  7235. * A render target used in context of {@link WebGLRenderer}.
  7236. *
  7237. * @augments RenderTarget
  7238. */
  7239. class WebGLRenderTarget extends RenderTarget {
  7240. /**
  7241. * Constructs a new 3D render target.
  7242. *
  7243. * @param {number} [width=1] - The width of the render target.
  7244. * @param {number} [height=1] - The height of the render target.
  7245. * @param {RenderTarget~Options} [options] - The configuration object.
  7246. */
  7247. constructor( width = 1, height = 1, options = {} ) {
  7248. super( width, height, options );
  7249. /**
  7250. * This flag can be used for type testing.
  7251. *
  7252. * @type {boolean}
  7253. * @readonly
  7254. * @default true
  7255. */
  7256. this.isWebGLRenderTarget = true;
  7257. }
  7258. }
  7259. /**
  7260. * Creates an array of textures directly from raw buffer data.
  7261. *
  7262. * @augments Texture
  7263. */
  7264. class DataArrayTexture extends Texture {
  7265. /**
  7266. * Constructs a new data array texture.
  7267. *
  7268. * @param {?TypedArray} [data=null] - The buffer data.
  7269. * @param {number} [width=1] - The width of the texture.
  7270. * @param {number} [height=1] - The height of the texture.
  7271. * @param {number} [depth=1] - The depth of the texture.
  7272. */
  7273. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7274. super( null );
  7275. /**
  7276. * This flag can be used for type testing.
  7277. *
  7278. * @type {boolean}
  7279. * @readonly
  7280. * @default true
  7281. */
  7282. this.isDataArrayTexture = true;
  7283. /**
  7284. * The image definition of a data texture.
  7285. *
  7286. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7287. */
  7288. this.image = { data, width, height, depth };
  7289. /**
  7290. * How the texture is sampled when a texel covers more than one pixel.
  7291. *
  7292. * Overwritten and set to `NearestFilter` by default.
  7293. *
  7294. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7295. * @default NearestFilter
  7296. */
  7297. this.magFilter = NearestFilter;
  7298. /**
  7299. * How the texture is sampled when a texel covers less than one pixel.
  7300. *
  7301. * Overwritten and set to `NearestFilter` by default.
  7302. *
  7303. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7304. * @default NearestFilter
  7305. */
  7306. this.minFilter = NearestFilter;
  7307. /**
  7308. * This defines how the texture is wrapped in the depth and corresponds to
  7309. * *W* in UVW mapping.
  7310. *
  7311. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7312. * @default ClampToEdgeWrapping
  7313. */
  7314. this.wrapR = ClampToEdgeWrapping;
  7315. /**
  7316. * Whether to generate mipmaps (if possible) for a texture.
  7317. *
  7318. * Overwritten and set to `false` by default.
  7319. *
  7320. * @type {boolean}
  7321. * @default false
  7322. */
  7323. this.generateMipmaps = false;
  7324. /**
  7325. * If set to `true`, the texture is flipped along the vertical axis when
  7326. * uploaded to the GPU.
  7327. *
  7328. * Overwritten and set to `false` by default.
  7329. *
  7330. * @type {boolean}
  7331. * @default false
  7332. */
  7333. this.flipY = false;
  7334. /**
  7335. * Specifies the alignment requirements for the start of each pixel row in memory.
  7336. *
  7337. * Overwritten and set to `1` by default.
  7338. *
  7339. * @type {boolean}
  7340. * @default 1
  7341. */
  7342. this.unpackAlignment = 1;
  7343. /**
  7344. * A set of all layers which need to be updated in the texture.
  7345. *
  7346. * @type {Set<number>}
  7347. */
  7348. this.layerUpdates = new Set();
  7349. }
  7350. /**
  7351. * Describes that a specific layer of the texture needs to be updated.
  7352. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7353. * entire data texture array is sent to the GPU. Marking specific
  7354. * layers will only transmit subsets of all mipmaps associated with a
  7355. * specific depth in the array which is often much more performant.
  7356. *
  7357. * @param {number} layerIndex - The layer index that should be updated.
  7358. */
  7359. addLayerUpdate( layerIndex ) {
  7360. this.layerUpdates.add( layerIndex );
  7361. }
  7362. /**
  7363. * Resets the layer updates registry.
  7364. */
  7365. clearLayerUpdates() {
  7366. this.layerUpdates.clear();
  7367. }
  7368. }
  7369. /**
  7370. * An array render target used in context of {@link WebGLRenderer}.
  7371. *
  7372. * @augments WebGLRenderTarget
  7373. */
  7374. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7375. /**
  7376. * Constructs a new array render target.
  7377. *
  7378. * @param {number} [width=1] - The width of the render target.
  7379. * @param {number} [height=1] - The height of the render target.
  7380. * @param {number} [depth=1] - The height of the render target.
  7381. * @param {RenderTarget~Options} [options] - The configuration object.
  7382. */
  7383. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7384. super( width, height, options );
  7385. /**
  7386. * This flag can be used for type testing.
  7387. *
  7388. * @type {boolean}
  7389. * @readonly
  7390. * @default true
  7391. */
  7392. this.isWebGLArrayRenderTarget = true;
  7393. this.depth = depth;
  7394. /**
  7395. * Overwritten with a different texture type.
  7396. *
  7397. * @type {DataArrayTexture}
  7398. */
  7399. this.texture = new DataArrayTexture( null, width, height, depth );
  7400. this._setTextureOptions( options );
  7401. this.texture.isRenderTargetTexture = true;
  7402. }
  7403. }
  7404. /**
  7405. * Creates a three-dimensional texture from raw data, with parameters to
  7406. * divide it into width, height, and depth.
  7407. *
  7408. * @augments Texture
  7409. */
  7410. class Data3DTexture extends Texture {
  7411. /**
  7412. * Constructs a new data array texture.
  7413. *
  7414. * @param {?TypedArray} [data=null] - The buffer data.
  7415. * @param {number} [width=1] - The width of the texture.
  7416. * @param {number} [height=1] - The height of the texture.
  7417. * @param {number} [depth=1] - The depth of the texture.
  7418. */
  7419. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7420. // We're going to add .setXXX() methods for setting properties later.
  7421. // Users can still set in Data3DTexture directly.
  7422. //
  7423. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7424. // texture.anisotropy = 16;
  7425. //
  7426. // See #14839
  7427. super( null );
  7428. /**
  7429. * This flag can be used for type testing.
  7430. *
  7431. * @type {boolean}
  7432. * @readonly
  7433. * @default true
  7434. */
  7435. this.isData3DTexture = true;
  7436. /**
  7437. * The image definition of a data texture.
  7438. *
  7439. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7440. */
  7441. this.image = { data, width, height, depth };
  7442. /**
  7443. * How the texture is sampled when a texel covers more than one pixel.
  7444. *
  7445. * Overwritten and set to `NearestFilter` by default.
  7446. *
  7447. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7448. * @default NearestFilter
  7449. */
  7450. this.magFilter = NearestFilter;
  7451. /**
  7452. * How the texture is sampled when a texel covers less than one pixel.
  7453. *
  7454. * Overwritten and set to `NearestFilter` by default.
  7455. *
  7456. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7457. * @default NearestFilter
  7458. */
  7459. this.minFilter = NearestFilter;
  7460. /**
  7461. * This defines how the texture is wrapped in the depth and corresponds to
  7462. * *W* in UVW mapping.
  7463. *
  7464. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7465. * @default ClampToEdgeWrapping
  7466. */
  7467. this.wrapR = ClampToEdgeWrapping;
  7468. /**
  7469. * Whether to generate mipmaps (if possible) for a texture.
  7470. *
  7471. * Overwritten and set to `false` by default.
  7472. *
  7473. * @type {boolean}
  7474. * @default false
  7475. */
  7476. this.generateMipmaps = false;
  7477. /**
  7478. * If set to `true`, the texture is flipped along the vertical axis when
  7479. * uploaded to the GPU.
  7480. *
  7481. * Overwritten and set to `false` by default.
  7482. *
  7483. * @type {boolean}
  7484. * @default false
  7485. */
  7486. this.flipY = false;
  7487. /**
  7488. * Specifies the alignment requirements for the start of each pixel row in memory.
  7489. *
  7490. * Overwritten and set to `1` by default.
  7491. *
  7492. * @type {boolean}
  7493. * @default 1
  7494. */
  7495. this.unpackAlignment = 1;
  7496. }
  7497. }
  7498. /**
  7499. * A 3D render target used in context of {@link WebGLRenderer}.
  7500. *
  7501. * @augments WebGLRenderTarget
  7502. */
  7503. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7504. /**
  7505. * Constructs a new 3D render target.
  7506. *
  7507. * @param {number} [width=1] - The width of the render target.
  7508. * @param {number} [height=1] - The height of the render target.
  7509. * @param {number} [depth=1] - The height of the render target.
  7510. * @param {RenderTarget~Options} [options] - The configuration object.
  7511. */
  7512. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7513. super( width, height, options );
  7514. /**
  7515. * This flag can be used for type testing.
  7516. *
  7517. * @type {boolean}
  7518. * @readonly
  7519. * @default true
  7520. */
  7521. this.isWebGL3DRenderTarget = true;
  7522. this.depth = depth;
  7523. /**
  7524. * Overwritten with a different texture type.
  7525. *
  7526. * @type {Data3DTexture}
  7527. */
  7528. this.texture = new Data3DTexture( null, width, height, depth );
  7529. this._setTextureOptions( options );
  7530. this.texture.isRenderTargetTexture = true;
  7531. }
  7532. }
  7533. /**
  7534. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7535. */
  7536. class Box3 {
  7537. /**
  7538. * Constructs a new bounding box.
  7539. *
  7540. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7541. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7542. */
  7543. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7544. /**
  7545. * This flag can be used for type testing.
  7546. *
  7547. * @type {boolean}
  7548. * @readonly
  7549. * @default true
  7550. */
  7551. this.isBox3 = true;
  7552. /**
  7553. * The lower boundary of the box.
  7554. *
  7555. * @type {Vector3}
  7556. */
  7557. this.min = min;
  7558. /**
  7559. * The upper boundary of the box.
  7560. *
  7561. * @type {Vector3}
  7562. */
  7563. this.max = max;
  7564. }
  7565. /**
  7566. * Sets the lower and upper boundaries of this box.
  7567. * Please note that this method only copies the values from the given objects.
  7568. *
  7569. * @param {Vector3} min - The lower boundary of the box.
  7570. * @param {Vector3} max - The upper boundary of the box.
  7571. * @return {Box3} A reference to this bounding box.
  7572. */
  7573. set( min, max ) {
  7574. this.min.copy( min );
  7575. this.max.copy( max );
  7576. return this;
  7577. }
  7578. /**
  7579. * Sets the upper and lower bounds of this box so it encloses the position data
  7580. * in the given array.
  7581. *
  7582. * @param {Array<number>} array - An array holding 3D position data.
  7583. * @return {Box3} A reference to this bounding box.
  7584. */
  7585. setFromArray( array ) {
  7586. this.makeEmpty();
  7587. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7588. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7589. }
  7590. return this;
  7591. }
  7592. /**
  7593. * Sets the upper and lower bounds of this box so it encloses the position data
  7594. * in the given buffer attribute.
  7595. *
  7596. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7597. * @return {Box3} A reference to this bounding box.
  7598. */
  7599. setFromBufferAttribute( attribute ) {
  7600. this.makeEmpty();
  7601. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7602. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7603. }
  7604. return this;
  7605. }
  7606. /**
  7607. * Sets the upper and lower bounds of this box so it encloses the position data
  7608. * in the given array.
  7609. *
  7610. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7611. * @return {Box3} A reference to this bounding box.
  7612. */
  7613. setFromPoints( points ) {
  7614. this.makeEmpty();
  7615. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7616. this.expandByPoint( points[ i ] );
  7617. }
  7618. return this;
  7619. }
  7620. /**
  7621. * Centers this box on the given center vector and sets this box's width, height and
  7622. * depth to the given size values.
  7623. *
  7624. * @param {Vector3} center - The center of the box.
  7625. * @param {Vector3} size - The x, y and z dimensions of the box.
  7626. * @return {Box3} A reference to this bounding box.
  7627. */
  7628. setFromCenterAndSize( center, size ) {
  7629. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7630. this.min.copy( center ).sub( halfSize );
  7631. this.max.copy( center ).add( halfSize );
  7632. return this;
  7633. }
  7634. /**
  7635. * Computes the world-axis-aligned bounding box for the given 3D object
  7636. * (including its children), accounting for the object's, and children's,
  7637. * world transforms. The function may result in a larger box than strictly necessary.
  7638. *
  7639. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7640. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7641. * world-axis-aligned bounding box at the expense of more computation.
  7642. * @return {Box3} A reference to this bounding box.
  7643. */
  7644. setFromObject( object, precise = false ) {
  7645. this.makeEmpty();
  7646. return this.expandByObject( object, precise );
  7647. }
  7648. /**
  7649. * Returns a new box with copied values from this instance.
  7650. *
  7651. * @return {Box3} A clone of this instance.
  7652. */
  7653. clone() {
  7654. return new this.constructor().copy( this );
  7655. }
  7656. /**
  7657. * Copies the values of the given box to this instance.
  7658. *
  7659. * @param {Box3} box - The box to copy.
  7660. * @return {Box3} A reference to this bounding box.
  7661. */
  7662. copy( box ) {
  7663. this.min.copy( box.min );
  7664. this.max.copy( box.max );
  7665. return this;
  7666. }
  7667. /**
  7668. * Makes this box empty which means in encloses a zero space in 3D.
  7669. *
  7670. * @return {Box3} A reference to this bounding box.
  7671. */
  7672. makeEmpty() {
  7673. this.min.x = this.min.y = this.min.z = + Infinity;
  7674. this.max.x = this.max.y = this.max.z = - Infinity;
  7675. return this;
  7676. }
  7677. /**
  7678. * Returns true if this box includes zero points within its bounds.
  7679. * Note that a box with equal lower and upper bounds still includes one
  7680. * point, the one both bounds share.
  7681. *
  7682. * @return {boolean} Whether this box is empty or not.
  7683. */
  7684. isEmpty() {
  7685. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7686. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7687. }
  7688. /**
  7689. * Returns the center point of this box.
  7690. *
  7691. * @param {Vector3} target - The target vector that is used to store the method's result.
  7692. * @return {Vector3} The center point.
  7693. */
  7694. getCenter( target ) {
  7695. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7696. }
  7697. /**
  7698. * Returns the dimensions of this box.
  7699. *
  7700. * @param {Vector3} target - The target vector that is used to store the method's result.
  7701. * @return {Vector3} The size.
  7702. */
  7703. getSize( target ) {
  7704. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7705. }
  7706. /**
  7707. * Expands the boundaries of this box to include the given point.
  7708. *
  7709. * @param {Vector3} point - The point that should be included by the bounding box.
  7710. * @return {Box3} A reference to this bounding box.
  7711. */
  7712. expandByPoint( point ) {
  7713. this.min.min( point );
  7714. this.max.max( point );
  7715. return this;
  7716. }
  7717. /**
  7718. * Expands this box equilaterally by the given vector. The width of this
  7719. * box will be expanded by the x component of the vector in both
  7720. * directions. The height of this box will be expanded by the y component of
  7721. * the vector in both directions. The depth of this box will be
  7722. * expanded by the z component of the vector in both directions.
  7723. *
  7724. * @param {Vector3} vector - The vector that should expand the bounding box.
  7725. * @return {Box3} A reference to this bounding box.
  7726. */
  7727. expandByVector( vector ) {
  7728. this.min.sub( vector );
  7729. this.max.add( vector );
  7730. return this;
  7731. }
  7732. /**
  7733. * Expands each dimension of the box by the given scalar. If negative, the
  7734. * dimensions of the box will be contracted.
  7735. *
  7736. * @param {number} scalar - The scalar value that should expand the bounding box.
  7737. * @return {Box3} A reference to this bounding box.
  7738. */
  7739. expandByScalar( scalar ) {
  7740. this.min.addScalar( - scalar );
  7741. this.max.addScalar( scalar );
  7742. return this;
  7743. }
  7744. /**
  7745. * Expands the boundaries of this box to include the given 3D object and
  7746. * its children, accounting for the object's, and children's, world
  7747. * transforms. The function may result in a larger box than strictly
  7748. * necessary (unless the precise parameter is set to true).
  7749. *
  7750. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7751. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7752. * as little as necessary at the expense of more computation.
  7753. * @return {Box3} A reference to this bounding box.
  7754. */
  7755. expandByObject( object, precise = false ) {
  7756. // Computes the world-axis-aligned bounding box of an object (including its children),
  7757. // accounting for both the object's, and children's, world transforms
  7758. object.updateWorldMatrix( false, false );
  7759. const geometry = object.geometry;
  7760. if ( geometry !== undefined ) {
  7761. const positionAttribute = geometry.getAttribute( 'position' );
  7762. // precise AABB computation based on vertex data requires at least a position attribute.
  7763. // instancing isn't supported so far and uses the normal (conservative) code path.
  7764. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7765. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7766. if ( object.isMesh === true ) {
  7767. object.getVertexPosition( i, _vector$b );
  7768. } else {
  7769. _vector$b.fromBufferAttribute( positionAttribute, i );
  7770. }
  7771. _vector$b.applyMatrix4( object.matrixWorld );
  7772. this.expandByPoint( _vector$b );
  7773. }
  7774. } else {
  7775. if ( object.boundingBox !== undefined ) {
  7776. // object-level bounding box
  7777. if ( object.boundingBox === null ) {
  7778. object.computeBoundingBox();
  7779. }
  7780. _box$4.copy( object.boundingBox );
  7781. } else {
  7782. // geometry-level bounding box
  7783. if ( geometry.boundingBox === null ) {
  7784. geometry.computeBoundingBox();
  7785. }
  7786. _box$4.copy( geometry.boundingBox );
  7787. }
  7788. _box$4.applyMatrix4( object.matrixWorld );
  7789. this.union( _box$4 );
  7790. }
  7791. }
  7792. const children = object.children;
  7793. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7794. this.expandByObject( children[ i ], precise );
  7795. }
  7796. return this;
  7797. }
  7798. /**
  7799. * Returns `true` if the given point lies within or on the boundaries of this box.
  7800. *
  7801. * @param {Vector3} point - The point to test.
  7802. * @return {boolean} Whether the bounding box contains the given point or not.
  7803. */
  7804. containsPoint( point ) {
  7805. return point.x >= this.min.x && point.x <= this.max.x &&
  7806. point.y >= this.min.y && point.y <= this.max.y &&
  7807. point.z >= this.min.z && point.z <= this.max.z;
  7808. }
  7809. /**
  7810. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7811. * If this box and the given one are identical, this function also returns `true`.
  7812. *
  7813. * @param {Box3} box - The bounding box to test.
  7814. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7815. */
  7816. containsBox( box ) {
  7817. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7818. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7819. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7820. }
  7821. /**
  7822. * Returns a point as a proportion of this box's width, height and depth.
  7823. *
  7824. * @param {Vector3} point - A point in 3D space.
  7825. * @param {Vector3} target - The target vector that is used to store the method's result.
  7826. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7827. */
  7828. getParameter( point, target ) {
  7829. // This can potentially have a divide by zero if the box
  7830. // has a size dimension of 0.
  7831. return target.set(
  7832. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7833. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7834. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7835. );
  7836. }
  7837. /**
  7838. * Returns `true` if the given bounding box intersects with this bounding box.
  7839. *
  7840. * @param {Box3} box - The bounding box to test.
  7841. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7842. */
  7843. intersectsBox( box ) {
  7844. // using 6 splitting planes to rule out intersections.
  7845. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7846. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7847. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7848. }
  7849. /**
  7850. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7851. *
  7852. * @param {Sphere} sphere - The bounding sphere to test.
  7853. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7854. */
  7855. intersectsSphere( sphere ) {
  7856. // Find the point on the AABB closest to the sphere center.
  7857. this.clampPoint( sphere.center, _vector$b );
  7858. // If that point is inside the sphere, the AABB and sphere intersect.
  7859. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7860. }
  7861. /**
  7862. * Returns `true` if the given plane intersects with this bounding box.
  7863. *
  7864. * @param {Plane} plane - The plane to test.
  7865. * @return {boolean} Whether the given plane intersects with this bounding box.
  7866. */
  7867. intersectsPlane( plane ) {
  7868. // We compute the minimum and maximum dot product values. If those values
  7869. // are on the same side (back or front) of the plane, then there is no intersection.
  7870. let min, max;
  7871. if ( plane.normal.x > 0 ) {
  7872. min = plane.normal.x * this.min.x;
  7873. max = plane.normal.x * this.max.x;
  7874. } else {
  7875. min = plane.normal.x * this.max.x;
  7876. max = plane.normal.x * this.min.x;
  7877. }
  7878. if ( plane.normal.y > 0 ) {
  7879. min += plane.normal.y * this.min.y;
  7880. max += plane.normal.y * this.max.y;
  7881. } else {
  7882. min += plane.normal.y * this.max.y;
  7883. max += plane.normal.y * this.min.y;
  7884. }
  7885. if ( plane.normal.z > 0 ) {
  7886. min += plane.normal.z * this.min.z;
  7887. max += plane.normal.z * this.max.z;
  7888. } else {
  7889. min += plane.normal.z * this.max.z;
  7890. max += plane.normal.z * this.min.z;
  7891. }
  7892. return ( min <= - plane.constant && max >= - plane.constant );
  7893. }
  7894. /**
  7895. * Returns `true` if the given triangle intersects with this bounding box.
  7896. *
  7897. * @param {Triangle} triangle - The triangle to test.
  7898. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7899. */
  7900. intersectsTriangle( triangle ) {
  7901. if ( this.isEmpty() ) {
  7902. return false;
  7903. }
  7904. // compute box center and extents
  7905. this.getCenter( _center );
  7906. _extents.subVectors( this.max, _center );
  7907. // translate triangle to aabb origin
  7908. _v0$3.subVectors( triangle.a, _center );
  7909. _v1$7.subVectors( triangle.b, _center );
  7910. _v2$4.subVectors( triangle.c, _center );
  7911. // compute edge vectors for triangle
  7912. _f0.subVectors( _v1$7, _v0$3 );
  7913. _f1.subVectors( _v2$4, _v1$7 );
  7914. _f2.subVectors( _v0$3, _v2$4 );
  7915. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7916. // 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
  7917. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7918. let axes = [
  7919. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7920. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7921. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7922. ];
  7923. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7924. return false;
  7925. }
  7926. // test 3 face normals from the aabb
  7927. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7928. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7929. return false;
  7930. }
  7931. // finally testing the face normal of the triangle
  7932. // use already existing triangle edge vectors here
  7933. _triangleNormal.crossVectors( _f0, _f1 );
  7934. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7935. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7936. }
  7937. /**
  7938. * Clamps the given point within the bounds of this box.
  7939. *
  7940. * @param {Vector3} point - The point to clamp.
  7941. * @param {Vector3} target - The target vector that is used to store the method's result.
  7942. * @return {Vector3} The clamped point.
  7943. */
  7944. clampPoint( point, target ) {
  7945. return target.copy( point ).clamp( this.min, this.max );
  7946. }
  7947. /**
  7948. * Returns the euclidean distance from any edge of this box to the specified point. If
  7949. * the given point lies inside of this box, the distance will be `0`.
  7950. *
  7951. * @param {Vector3} point - The point to compute the distance to.
  7952. * @return {number} The euclidean distance.
  7953. */
  7954. distanceToPoint( point ) {
  7955. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7956. }
  7957. /**
  7958. * Returns a bounding sphere that encloses this bounding box.
  7959. *
  7960. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7961. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7962. */
  7963. getBoundingSphere( target ) {
  7964. if ( this.isEmpty() ) {
  7965. target.makeEmpty();
  7966. } else {
  7967. this.getCenter( target.center );
  7968. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7969. }
  7970. return target;
  7971. }
  7972. /**
  7973. * Computes the intersection of this bounding box and the given one, setting the upper
  7974. * bound of this box to the lesser of the two boxes' upper bounds and the
  7975. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7976. * there's no overlap, makes this box empty.
  7977. *
  7978. * @param {Box3} box - The bounding box to intersect with.
  7979. * @return {Box3} A reference to this bounding box.
  7980. */
  7981. intersect( box ) {
  7982. this.min.max( box.min );
  7983. this.max.min( box.max );
  7984. // 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.
  7985. if ( this.isEmpty() ) this.makeEmpty();
  7986. return this;
  7987. }
  7988. /**
  7989. * Computes the union of this box and another and the given one, setting the upper
  7990. * bound of this box to the greater of the two boxes' upper bounds and the
  7991. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7992. *
  7993. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7994. * @return {Box3} A reference to this bounding box.
  7995. */
  7996. union( box ) {
  7997. this.min.min( box.min );
  7998. this.max.max( box.max );
  7999. return this;
  8000. }
  8001. /**
  8002. * Transforms this bounding box by the given 4x4 transformation matrix.
  8003. *
  8004. * @param {Matrix4} matrix - The transformation matrix.
  8005. * @return {Box3} A reference to this bounding box.
  8006. */
  8007. applyMatrix4( matrix ) {
  8008. // transform of empty box is an empty box.
  8009. if ( this.isEmpty() ) return this;
  8010. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8011. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  8012. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  8013. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  8014. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  8015. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  8016. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  8017. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  8018. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  8019. this.setFromPoints( _points );
  8020. return this;
  8021. }
  8022. /**
  8023. * Adds the given offset to both the upper and lower bounds of this bounding box,
  8024. * effectively moving it in 3D space.
  8025. *
  8026. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  8027. * @return {Box3} A reference to this bounding box.
  8028. */
  8029. translate( offset ) {
  8030. this.min.add( offset );
  8031. this.max.add( offset );
  8032. return this;
  8033. }
  8034. /**
  8035. * Returns `true` if this bounding box is equal with the given one.
  8036. *
  8037. * @param {Box3} box - The box to test for equality.
  8038. * @return {boolean} Whether this bounding box is equal with the given one.
  8039. */
  8040. equals( box ) {
  8041. return box.min.equals( this.min ) && box.max.equals( this.max );
  8042. }
  8043. /**
  8044. * Returns a serialized structure of the bounding box.
  8045. *
  8046. * @return {Object} Serialized structure with fields representing the object state.
  8047. */
  8048. toJSON() {
  8049. return {
  8050. min: this.min.toArray(),
  8051. max: this.max.toArray()
  8052. };
  8053. }
  8054. /**
  8055. * Returns a serialized structure of the bounding box.
  8056. *
  8057. * @param {Object} json - The serialized json to set the box from.
  8058. * @return {Box3} A reference to this bounding box.
  8059. */
  8060. fromJSON( json ) {
  8061. this.min.fromArray( json.min );
  8062. this.max.fromArray( json.max );
  8063. return this;
  8064. }
  8065. }
  8066. const _points = [
  8067. /*@__PURE__*/ new Vector3(),
  8068. /*@__PURE__*/ new Vector3(),
  8069. /*@__PURE__*/ new Vector3(),
  8070. /*@__PURE__*/ new Vector3(),
  8071. /*@__PURE__*/ new Vector3(),
  8072. /*@__PURE__*/ new Vector3(),
  8073. /*@__PURE__*/ new Vector3(),
  8074. /*@__PURE__*/ new Vector3()
  8075. ];
  8076. const _vector$b = /*@__PURE__*/ new Vector3();
  8077. const _box$4 = /*@__PURE__*/ new Box3();
  8078. // triangle centered vertices
  8079. const _v0$3 = /*@__PURE__*/ new Vector3();
  8080. const _v1$7 = /*@__PURE__*/ new Vector3();
  8081. const _v2$4 = /*@__PURE__*/ new Vector3();
  8082. // triangle edge vectors
  8083. const _f0 = /*@__PURE__*/ new Vector3();
  8084. const _f1 = /*@__PURE__*/ new Vector3();
  8085. const _f2 = /*@__PURE__*/ new Vector3();
  8086. const _center = /*@__PURE__*/ new Vector3();
  8087. const _extents = /*@__PURE__*/ new Vector3();
  8088. const _triangleNormal = /*@__PURE__*/ new Vector3();
  8089. const _testAxis = /*@__PURE__*/ new Vector3();
  8090. function satForAxes( axes, v0, v1, v2, extents ) {
  8091. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  8092. _testAxis.fromArray( axes, i );
  8093. // project the aabb onto the separating axis
  8094. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  8095. // project all 3 vertices of the triangle onto the separating axis
  8096. const p0 = v0.dot( _testAxis );
  8097. const p1 = v1.dot( _testAxis );
  8098. const p2 = v2.dot( _testAxis );
  8099. // actual test, basically see if either of the most extreme of the triangle points intersects r
  8100. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  8101. // points of the projected triangle are outside the projected half-length of the aabb
  8102. // the axis is separating and we can exit
  8103. return false;
  8104. }
  8105. }
  8106. return true;
  8107. }
  8108. const _box$3 = /*@__PURE__*/ new Box3();
  8109. const _v1$6 = /*@__PURE__*/ new Vector3();
  8110. const _v2$3 = /*@__PURE__*/ new Vector3();
  8111. /**
  8112. * An analytical 3D sphere defined by a center and radius. This class is mainly
  8113. * used as a Bounding Sphere for 3D objects.
  8114. */
  8115. class Sphere {
  8116. /**
  8117. * Constructs a new sphere.
  8118. *
  8119. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  8120. * @param {number} [radius=-1] - The radius of the sphere.
  8121. */
  8122. constructor( center = new Vector3(), radius = -1 ) {
  8123. /**
  8124. * This flag can be used for type testing.
  8125. *
  8126. * @type {boolean}
  8127. * @readonly
  8128. * @default true
  8129. */
  8130. this.isSphere = true;
  8131. /**
  8132. * The center of the sphere
  8133. *
  8134. * @type {Vector3}
  8135. */
  8136. this.center = center;
  8137. /**
  8138. * The radius of the sphere.
  8139. *
  8140. * @type {number}
  8141. */
  8142. this.radius = radius;
  8143. }
  8144. /**
  8145. * Sets the sphere's components by copying the given values.
  8146. *
  8147. * @param {Vector3} center - The center.
  8148. * @param {number} radius - The radius.
  8149. * @return {Sphere} A reference to this sphere.
  8150. */
  8151. set( center, radius ) {
  8152. this.center.copy( center );
  8153. this.radius = radius;
  8154. return this;
  8155. }
  8156. /**
  8157. * Computes the minimum bounding sphere for list of points.
  8158. * If the optional center point is given, it is used as the sphere's
  8159. * center. Otherwise, the center of the axis-aligned bounding box
  8160. * encompassing the points is calculated.
  8161. *
  8162. * @param {Array<Vector3>} points - A list of points in 3D space.
  8163. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8164. * @return {Sphere} A reference to this sphere.
  8165. */
  8166. setFromPoints( points, optionalCenter ) {
  8167. const center = this.center;
  8168. if ( optionalCenter !== undefined ) {
  8169. center.copy( optionalCenter );
  8170. } else {
  8171. _box$3.setFromPoints( points ).getCenter( center );
  8172. }
  8173. let maxRadiusSq = 0;
  8174. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8175. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8176. }
  8177. this.radius = Math.sqrt( maxRadiusSq );
  8178. return this;
  8179. }
  8180. /**
  8181. * Copies the values of the given sphere to this instance.
  8182. *
  8183. * @param {Sphere} sphere - The sphere to copy.
  8184. * @return {Sphere} A reference to this sphere.
  8185. */
  8186. copy( sphere ) {
  8187. this.center.copy( sphere.center );
  8188. this.radius = sphere.radius;
  8189. return this;
  8190. }
  8191. /**
  8192. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8193. *
  8194. * Spheres with a radius of `0` contain only their center point and are not
  8195. * considered to be empty.
  8196. *
  8197. * @return {boolean} Whether this sphere is empty or not.
  8198. */
  8199. isEmpty() {
  8200. return ( this.radius < 0 );
  8201. }
  8202. /**
  8203. * Makes this sphere empty which means in encloses a zero space in 3D.
  8204. *
  8205. * @return {Sphere} A reference to this sphere.
  8206. */
  8207. makeEmpty() {
  8208. this.center.set( 0, 0, 0 );
  8209. this.radius = -1;
  8210. return this;
  8211. }
  8212. /**
  8213. * Returns `true` if this sphere contains the given point inclusive of
  8214. * the surface of the sphere.
  8215. *
  8216. * @param {Vector3} point - The point to check.
  8217. * @return {boolean} Whether this sphere contains the given point or not.
  8218. */
  8219. containsPoint( point ) {
  8220. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8221. }
  8222. /**
  8223. * Returns the closest distance from the boundary of the sphere to the
  8224. * given point. If the sphere contains the point, the distance will
  8225. * be negative.
  8226. *
  8227. * @param {Vector3} point - The point to compute the distance to.
  8228. * @return {number} The distance to the point.
  8229. */
  8230. distanceToPoint( point ) {
  8231. return ( point.distanceTo( this.center ) - this.radius );
  8232. }
  8233. /**
  8234. * Returns `true` if this sphere intersects with the given one.
  8235. *
  8236. * @param {Sphere} sphere - The sphere to test.
  8237. * @return {boolean} Whether this sphere intersects with the given one or not.
  8238. */
  8239. intersectsSphere( sphere ) {
  8240. const radiusSum = this.radius + sphere.radius;
  8241. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8242. }
  8243. /**
  8244. * Returns `true` if this sphere intersects with the given box.
  8245. *
  8246. * @param {Box3} box - The box to test.
  8247. * @return {boolean} Whether this sphere intersects with the given box or not.
  8248. */
  8249. intersectsBox( box ) {
  8250. return box.intersectsSphere( this );
  8251. }
  8252. /**
  8253. * Returns `true` if this sphere intersects with the given plane.
  8254. *
  8255. * @param {Plane} plane - The plane to test.
  8256. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8257. */
  8258. intersectsPlane( plane ) {
  8259. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8260. }
  8261. /**
  8262. * Clamps a point within the sphere. If the point is outside the sphere, it
  8263. * will clamp it to the closest point on the edge of the sphere. Points
  8264. * already inside the sphere will not be affected.
  8265. *
  8266. * @param {Vector3} point - The plane to clamp.
  8267. * @param {Vector3} target - The target vector that is used to store the method's result.
  8268. * @return {Vector3} The clamped point.
  8269. */
  8270. clampPoint( point, target ) {
  8271. const deltaLengthSq = this.center.distanceToSquared( point );
  8272. target.copy( point );
  8273. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8274. target.sub( this.center ).normalize();
  8275. target.multiplyScalar( this.radius ).add( this.center );
  8276. }
  8277. return target;
  8278. }
  8279. /**
  8280. * Returns a bounding box that encloses this sphere.
  8281. *
  8282. * @param {Box3} target - The target box that is used to store the method's result.
  8283. * @return {Box3} The bounding box that encloses this sphere.
  8284. */
  8285. getBoundingBox( target ) {
  8286. if ( this.isEmpty() ) {
  8287. // Empty sphere produces empty bounding box
  8288. target.makeEmpty();
  8289. return target;
  8290. }
  8291. target.set( this.center, this.center );
  8292. target.expandByScalar( this.radius );
  8293. return target;
  8294. }
  8295. /**
  8296. * Transforms this sphere with the given 4x4 transformation matrix.
  8297. *
  8298. * @param {Matrix4} matrix - The transformation matrix.
  8299. * @return {Sphere} A reference to this sphere.
  8300. */
  8301. applyMatrix4( matrix ) {
  8302. this.center.applyMatrix4( matrix );
  8303. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8304. return this;
  8305. }
  8306. /**
  8307. * Translates the sphere's center by the given offset.
  8308. *
  8309. * @param {Vector3} offset - The offset.
  8310. * @return {Sphere} A reference to this sphere.
  8311. */
  8312. translate( offset ) {
  8313. this.center.add( offset );
  8314. return this;
  8315. }
  8316. /**
  8317. * Expands the boundaries of this sphere to include the given point.
  8318. *
  8319. * @param {Vector3} point - The point to include.
  8320. * @return {Sphere} A reference to this sphere.
  8321. */
  8322. expandByPoint( point ) {
  8323. if ( this.isEmpty() ) {
  8324. this.center.copy( point );
  8325. this.radius = 0;
  8326. return this;
  8327. }
  8328. _v1$6.subVectors( point, this.center );
  8329. const lengthSq = _v1$6.lengthSq();
  8330. if ( lengthSq > ( this.radius * this.radius ) ) {
  8331. // calculate the minimal sphere
  8332. const length = Math.sqrt( lengthSq );
  8333. const delta = ( length - this.radius ) * 0.5;
  8334. this.center.addScaledVector( _v1$6, delta / length );
  8335. this.radius += delta;
  8336. }
  8337. return this;
  8338. }
  8339. /**
  8340. * Expands this sphere to enclose both the original sphere and the given sphere.
  8341. *
  8342. * @param {Sphere} sphere - The sphere to include.
  8343. * @return {Sphere} A reference to this sphere.
  8344. */
  8345. union( sphere ) {
  8346. if ( sphere.isEmpty() ) {
  8347. return this;
  8348. }
  8349. if ( this.isEmpty() ) {
  8350. this.copy( sphere );
  8351. return this;
  8352. }
  8353. if ( this.center.equals( sphere.center ) === true ) {
  8354. this.radius = Math.max( this.radius, sphere.radius );
  8355. } else {
  8356. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8357. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8358. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8359. }
  8360. return this;
  8361. }
  8362. /**
  8363. * Returns `true` if this sphere is equal with the given one.
  8364. *
  8365. * @param {Sphere} sphere - The sphere to test for equality.
  8366. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8367. */
  8368. equals( sphere ) {
  8369. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8370. }
  8371. /**
  8372. * Returns a new sphere with copied values from this instance.
  8373. *
  8374. * @return {Sphere} A clone of this instance.
  8375. */
  8376. clone() {
  8377. return new this.constructor().copy( this );
  8378. }
  8379. /**
  8380. * Returns a serialized structure of the bounding sphere.
  8381. *
  8382. * @return {Object} Serialized structure with fields representing the object state.
  8383. */
  8384. toJSON() {
  8385. return {
  8386. radius: this.radius,
  8387. center: this.center.toArray()
  8388. };
  8389. }
  8390. /**
  8391. * Returns a serialized structure of the bounding sphere.
  8392. *
  8393. * @param {Object} json - The serialized json to set the sphere from.
  8394. * @return {Sphere} A reference to this bounding sphere.
  8395. */
  8396. fromJSON( json ) {
  8397. this.radius = json.radius;
  8398. this.center.fromArray( json.center );
  8399. return this;
  8400. }
  8401. }
  8402. const _vector$a = /*@__PURE__*/ new Vector3();
  8403. const _segCenter = /*@__PURE__*/ new Vector3();
  8404. const _segDir = /*@__PURE__*/ new Vector3();
  8405. const _diff = /*@__PURE__*/ new Vector3();
  8406. const _edge1 = /*@__PURE__*/ new Vector3();
  8407. const _edge2 = /*@__PURE__*/ new Vector3();
  8408. const _normal$1 = /*@__PURE__*/ new Vector3();
  8409. /**
  8410. * A ray that emits from an origin in a certain direction. The class is used by
  8411. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8412. * mouse picking (working out what objects in the 3D space the mouse is over)
  8413. * amongst other things.
  8414. */
  8415. class Ray {
  8416. /**
  8417. * Constructs a new ray.
  8418. *
  8419. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8420. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8421. */
  8422. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8423. /**
  8424. * The origin of the ray.
  8425. *
  8426. * @type {Vector3}
  8427. */
  8428. this.origin = origin;
  8429. /**
  8430. * The (normalized) direction of the ray.
  8431. *
  8432. * @type {Vector3}
  8433. */
  8434. this.direction = direction;
  8435. }
  8436. /**
  8437. * Sets the ray's components by copying the given values.
  8438. *
  8439. * @param {Vector3} origin - The origin.
  8440. * @param {Vector3} direction - The direction.
  8441. * @return {Ray} A reference to this ray.
  8442. */
  8443. set( origin, direction ) {
  8444. this.origin.copy( origin );
  8445. this.direction.copy( direction );
  8446. return this;
  8447. }
  8448. /**
  8449. * Copies the values of the given ray to this instance.
  8450. *
  8451. * @param {Ray} ray - The ray to copy.
  8452. * @return {Ray} A reference to this ray.
  8453. */
  8454. copy( ray ) {
  8455. this.origin.copy( ray.origin );
  8456. this.direction.copy( ray.direction );
  8457. return this;
  8458. }
  8459. /**
  8460. * Returns a vector that is located at a given distance along this ray.
  8461. *
  8462. * @param {number} t - The distance along the ray to retrieve a position for.
  8463. * @param {Vector3} target - The target vector that is used to store the method's result.
  8464. * @return {Vector3} A position on the ray.
  8465. */
  8466. at( t, target ) {
  8467. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8468. }
  8469. /**
  8470. * Adjusts the direction of the ray to point at the given vector in world space.
  8471. *
  8472. * @param {Vector3} v - The target position.
  8473. * @return {Ray} A reference to this ray.
  8474. */
  8475. lookAt( v ) {
  8476. this.direction.copy( v ).sub( this.origin ).normalize();
  8477. return this;
  8478. }
  8479. /**
  8480. * Shift the origin of this ray along its direction by the given distance.
  8481. *
  8482. * @param {number} t - The distance along the ray to interpolate.
  8483. * @return {Ray} A reference to this ray.
  8484. */
  8485. recast( t ) {
  8486. this.origin.copy( this.at( t, _vector$a ) );
  8487. return this;
  8488. }
  8489. /**
  8490. * Returns the point along this ray that is closest to the given point.
  8491. *
  8492. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8493. * @param {Vector3} target - The target vector that is used to store the method's result.
  8494. * @return {Vector3} The closest point on this ray.
  8495. */
  8496. closestPointToPoint( point, target ) {
  8497. target.subVectors( point, this.origin );
  8498. const directionDistance = target.dot( this.direction );
  8499. if ( directionDistance < 0 ) {
  8500. return target.copy( this.origin );
  8501. }
  8502. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8503. }
  8504. /**
  8505. * Returns the distance of the closest approach between this ray and the given point.
  8506. *
  8507. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8508. * @return {number} The distance.
  8509. */
  8510. distanceToPoint( point ) {
  8511. return Math.sqrt( this.distanceSqToPoint( point ) );
  8512. }
  8513. /**
  8514. * Returns the squared distance of the closest approach between this ray and the given point.
  8515. *
  8516. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8517. * @return {number} The squared distance.
  8518. */
  8519. distanceSqToPoint( point ) {
  8520. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8521. // point behind the ray
  8522. if ( directionDistance < 0 ) {
  8523. return this.origin.distanceToSquared( point );
  8524. }
  8525. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8526. return _vector$a.distanceToSquared( point );
  8527. }
  8528. /**
  8529. * Returns the squared distance between this ray and the given line segment.
  8530. *
  8531. * @param {Vector3} v0 - The start point of the line segment.
  8532. * @param {Vector3} v1 - The end point of the line segment.
  8533. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8534. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8535. * @return {number} The squared distance.
  8536. */
  8537. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8538. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8539. // It returns the min distance between the ray and the segment
  8540. // defined by v0 and v1
  8541. // It can also set two optional targets :
  8542. // - The closest point on the ray
  8543. // - The closest point on the segment
  8544. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8545. _segDir.copy( v1 ).sub( v0 ).normalize();
  8546. _diff.copy( this.origin ).sub( _segCenter );
  8547. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8548. const a01 = - this.direction.dot( _segDir );
  8549. const b0 = _diff.dot( this.direction );
  8550. const b1 = - _diff.dot( _segDir );
  8551. const c = _diff.lengthSq();
  8552. const det = Math.abs( 1 - a01 * a01 );
  8553. let s0, s1, sqrDist, extDet;
  8554. if ( det > 0 ) {
  8555. // The ray and segment are not parallel.
  8556. s0 = a01 * b1 - b0;
  8557. s1 = a01 * b0 - b1;
  8558. extDet = segExtent * det;
  8559. if ( s0 >= 0 ) {
  8560. if ( s1 >= - extDet ) {
  8561. if ( s1 <= extDet ) {
  8562. // region 0
  8563. // Minimum at interior points of ray and segment.
  8564. const invDet = 1 / det;
  8565. s0 *= invDet;
  8566. s1 *= invDet;
  8567. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8568. } else {
  8569. // region 1
  8570. s1 = segExtent;
  8571. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8572. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8573. }
  8574. } else {
  8575. // region 5
  8576. s1 = - segExtent;
  8577. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8578. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8579. }
  8580. } else {
  8581. if ( s1 <= - extDet ) {
  8582. // region 4
  8583. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8584. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8585. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8586. } else if ( s1 <= extDet ) {
  8587. // region 3
  8588. s0 = 0;
  8589. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8590. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8591. } else {
  8592. // region 2
  8593. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8594. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8595. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8596. }
  8597. }
  8598. } else {
  8599. // Ray and segment are parallel.
  8600. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8601. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8602. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8603. }
  8604. if ( optionalPointOnRay ) {
  8605. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8606. }
  8607. if ( optionalPointOnSegment ) {
  8608. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8609. }
  8610. return sqrDist;
  8611. }
  8612. /**
  8613. * Intersects this ray with the given sphere, returning the intersection
  8614. * point or `null` if there is no intersection.
  8615. *
  8616. * @param {Sphere} sphere - The sphere to intersect.
  8617. * @param {Vector3} target - The target vector that is used to store the method's result.
  8618. * @return {?Vector3} The intersection point.
  8619. */
  8620. intersectSphere( sphere, target ) {
  8621. _vector$a.subVectors( sphere.center, this.origin );
  8622. const tca = _vector$a.dot( this.direction );
  8623. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8624. const radius2 = sphere.radius * sphere.radius;
  8625. if ( d2 > radius2 ) return null;
  8626. const thc = Math.sqrt( radius2 - d2 );
  8627. // t0 = first intersect point - entrance on front of sphere
  8628. const t0 = tca - thc;
  8629. // t1 = second intersect point - exit point on back of sphere
  8630. const t1 = tca + thc;
  8631. // test to see if t1 is behind the ray - if so, return null
  8632. if ( t1 < 0 ) return null;
  8633. // test to see if t0 is behind the ray:
  8634. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8635. // in order to always return an intersect point that is in front of the ray.
  8636. if ( t0 < 0 ) return this.at( t1, target );
  8637. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8638. return this.at( t0, target );
  8639. }
  8640. /**
  8641. * Returns `true` if this ray intersects with the given sphere.
  8642. *
  8643. * @param {Sphere} sphere - The sphere to intersect.
  8644. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8645. */
  8646. intersectsSphere( sphere ) {
  8647. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8648. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8649. }
  8650. /**
  8651. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8652. * does not intersect with the plane.
  8653. *
  8654. * @param {Plane} plane - The plane to compute the distance to.
  8655. * @return {?number} Whether this ray intersects with the given sphere or not.
  8656. */
  8657. distanceToPlane( plane ) {
  8658. const denominator = plane.normal.dot( this.direction );
  8659. if ( denominator === 0 ) {
  8660. // line is coplanar, return origin
  8661. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8662. return 0;
  8663. }
  8664. // Null is preferable to undefined since undefined means.... it is undefined
  8665. return null;
  8666. }
  8667. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8668. // Return if the ray never intersects the plane
  8669. return t >= 0 ? t : null;
  8670. }
  8671. /**
  8672. * Intersects this ray with the given plane, returning the intersection
  8673. * point or `null` if there is no intersection.
  8674. *
  8675. * @param {Plane} plane - The plane to intersect.
  8676. * @param {Vector3} target - The target vector that is used to store the method's result.
  8677. * @return {?Vector3} The intersection point.
  8678. */
  8679. intersectPlane( plane, target ) {
  8680. const t = this.distanceToPlane( plane );
  8681. if ( t === null ) {
  8682. return null;
  8683. }
  8684. return this.at( t, target );
  8685. }
  8686. /**
  8687. * Returns `true` if this ray intersects with the given plane.
  8688. *
  8689. * @param {Plane} plane - The plane to intersect.
  8690. * @return {boolean} Whether this ray intersects with the given plane or not.
  8691. */
  8692. intersectsPlane( plane ) {
  8693. // check if the ray lies on the plane first
  8694. const distToPoint = plane.distanceToPoint( this.origin );
  8695. if ( distToPoint === 0 ) {
  8696. return true;
  8697. }
  8698. const denominator = plane.normal.dot( this.direction );
  8699. if ( denominator * distToPoint < 0 ) {
  8700. return true;
  8701. }
  8702. // ray origin is behind the plane (and is pointing behind it)
  8703. return false;
  8704. }
  8705. /**
  8706. * Intersects this ray with the given bounding box, returning the intersection
  8707. * point or `null` if there is no intersection.
  8708. *
  8709. * @param {Box3} box - The box to intersect.
  8710. * @param {Vector3} target - The target vector that is used to store the method's result.
  8711. * @return {?Vector3} The intersection point.
  8712. */
  8713. intersectBox( box, target ) {
  8714. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8715. const invdirx = 1 / this.direction.x,
  8716. invdiry = 1 / this.direction.y,
  8717. invdirz = 1 / this.direction.z;
  8718. const origin = this.origin;
  8719. if ( invdirx >= 0 ) {
  8720. tmin = ( box.min.x - origin.x ) * invdirx;
  8721. tmax = ( box.max.x - origin.x ) * invdirx;
  8722. } else {
  8723. tmin = ( box.max.x - origin.x ) * invdirx;
  8724. tmax = ( box.min.x - origin.x ) * invdirx;
  8725. }
  8726. if ( invdiry >= 0 ) {
  8727. tymin = ( box.min.y - origin.y ) * invdiry;
  8728. tymax = ( box.max.y - origin.y ) * invdiry;
  8729. } else {
  8730. tymin = ( box.max.y - origin.y ) * invdiry;
  8731. tymax = ( box.min.y - origin.y ) * invdiry;
  8732. }
  8733. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8734. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8735. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8736. if ( invdirz >= 0 ) {
  8737. tzmin = ( box.min.z - origin.z ) * invdirz;
  8738. tzmax = ( box.max.z - origin.z ) * invdirz;
  8739. } else {
  8740. tzmin = ( box.max.z - origin.z ) * invdirz;
  8741. tzmax = ( box.min.z - origin.z ) * invdirz;
  8742. }
  8743. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8744. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8745. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8746. //return point closest to the ray (positive side)
  8747. if ( tmax < 0 ) return null;
  8748. return this.at( tmin >= 0 ? tmin : tmax, target );
  8749. }
  8750. /**
  8751. * Returns `true` if this ray intersects with the given box.
  8752. *
  8753. * @param {Box3} box - The box to intersect.
  8754. * @return {boolean} Whether this ray intersects with the given box or not.
  8755. */
  8756. intersectsBox( box ) {
  8757. return this.intersectBox( box, _vector$a ) !== null;
  8758. }
  8759. /**
  8760. * Intersects this ray with the given triangle, returning the intersection
  8761. * point or `null` if there is no intersection.
  8762. *
  8763. * @param {Vector3} a - The first vertex of the triangle.
  8764. * @param {Vector3} b - The second vertex of the triangle.
  8765. * @param {Vector3} c - The third vertex of the triangle.
  8766. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8767. * @param {Vector3} target - The target vector that is used to store the method's result.
  8768. * @return {?Vector3} The intersection point.
  8769. */
  8770. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8771. // Compute the offset origin, edges, and normal.
  8772. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8773. _edge1.subVectors( b, a );
  8774. _edge2.subVectors( c, a );
  8775. _normal$1.crossVectors( _edge1, _edge2 );
  8776. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8777. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8778. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8779. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8780. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8781. let DdN = this.direction.dot( _normal$1 );
  8782. let sign;
  8783. if ( DdN > 0 ) {
  8784. if ( backfaceCulling ) return null;
  8785. sign = 1;
  8786. } else if ( DdN < 0 ) {
  8787. sign = -1;
  8788. DdN = - DdN;
  8789. } else {
  8790. return null;
  8791. }
  8792. _diff.subVectors( this.origin, a );
  8793. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8794. // b1 < 0, no intersection
  8795. if ( DdQxE2 < 0 ) {
  8796. return null;
  8797. }
  8798. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8799. // b2 < 0, no intersection
  8800. if ( DdE1xQ < 0 ) {
  8801. return null;
  8802. }
  8803. // b1+b2 > 1, no intersection
  8804. if ( DdQxE2 + DdE1xQ > DdN ) {
  8805. return null;
  8806. }
  8807. // Line intersects triangle, check if ray does.
  8808. const QdN = - sign * _diff.dot( _normal$1 );
  8809. // t < 0, no intersection
  8810. if ( QdN < 0 ) {
  8811. return null;
  8812. }
  8813. // Ray intersects triangle.
  8814. return this.at( QdN / DdN, target );
  8815. }
  8816. /**
  8817. * Transforms this ray with the given 4x4 transformation matrix.
  8818. *
  8819. * @param {Matrix4} matrix4 - The transformation matrix.
  8820. * @return {Ray} A reference to this ray.
  8821. */
  8822. applyMatrix4( matrix4 ) {
  8823. this.origin.applyMatrix4( matrix4 );
  8824. this.direction.transformDirection( matrix4 );
  8825. return this;
  8826. }
  8827. /**
  8828. * Returns `true` if this ray is equal with the given one.
  8829. *
  8830. * @param {Ray} ray - The ray to test for equality.
  8831. * @return {boolean} Whether this ray is equal with the given one.
  8832. */
  8833. equals( ray ) {
  8834. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8835. }
  8836. /**
  8837. * Returns a new ray with copied values from this instance.
  8838. *
  8839. * @return {Ray} A clone of this instance.
  8840. */
  8841. clone() {
  8842. return new this.constructor().copy( this );
  8843. }
  8844. }
  8845. /**
  8846. * Represents a 4x4 matrix.
  8847. *
  8848. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8849. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8850. *
  8851. * This allows a 3D vector representing a point in 3D space to undergo
  8852. * transformations such as translation, rotation, shear, scale, reflection,
  8853. * orthogonal or perspective projection and so on, by being multiplied by the
  8854. * matrix. This is known as `applying` the matrix to the vector.
  8855. *
  8856. * A Note on Row-Major and Column-Major Ordering:
  8857. *
  8858. * The constructor and {@link Matrix3#set} method take arguments in
  8859. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8860. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8861. * This means that calling:
  8862. * ```js
  8863. * const m = new THREE.Matrix4();
  8864. * m.set( 11, 12, 13, 14,
  8865. * 21, 22, 23, 24,
  8866. * 31, 32, 33, 34,
  8867. * 41, 42, 43, 44 );
  8868. * ```
  8869. * will result in the elements array containing:
  8870. * ```js
  8871. * m.elements = [ 11, 21, 31, 41,
  8872. * 12, 22, 32, 42,
  8873. * 13, 23, 33, 43,
  8874. * 14, 24, 34, 44 ];
  8875. * ```
  8876. * and internally all calculations are performed using column-major ordering.
  8877. * However, as the actual ordering makes no difference mathematically and
  8878. * most people are used to thinking about matrices in row-major order, the
  8879. * three.js documentation shows matrices in row-major order. Just bear in
  8880. * mind that if you are reading the source code, you'll have to take the
  8881. * transpose of any matrices outlined here to make sense of the calculations.
  8882. */
  8883. class Matrix4 {
  8884. /**
  8885. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8886. * in row-major order. If no arguments are provided, the constructor
  8887. * initializes the matrix as an identity matrix.
  8888. *
  8889. * @param {number} [n11] - 1-1 matrix element.
  8890. * @param {number} [n12] - 1-2 matrix element.
  8891. * @param {number} [n13] - 1-3 matrix element.
  8892. * @param {number} [n14] - 1-4 matrix element.
  8893. * @param {number} [n21] - 2-1 matrix element.
  8894. * @param {number} [n22] - 2-2 matrix element.
  8895. * @param {number} [n23] - 2-3 matrix element.
  8896. * @param {number} [n24] - 2-4 matrix element.
  8897. * @param {number} [n31] - 3-1 matrix element.
  8898. * @param {number} [n32] - 3-2 matrix element.
  8899. * @param {number} [n33] - 3-3 matrix element.
  8900. * @param {number} [n34] - 3-4 matrix element.
  8901. * @param {number} [n41] - 4-1 matrix element.
  8902. * @param {number} [n42] - 4-2 matrix element.
  8903. * @param {number} [n43] - 4-3 matrix element.
  8904. * @param {number} [n44] - 4-4 matrix element.
  8905. */
  8906. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8907. /**
  8908. * This flag can be used for type testing.
  8909. *
  8910. * @type {boolean}
  8911. * @readonly
  8912. * @default true
  8913. */
  8914. Matrix4.prototype.isMatrix4 = true;
  8915. /**
  8916. * A column-major list of matrix values.
  8917. *
  8918. * @type {Array<number>}
  8919. */
  8920. this.elements = [
  8921. 1, 0, 0, 0,
  8922. 0, 1, 0, 0,
  8923. 0, 0, 1, 0,
  8924. 0, 0, 0, 1
  8925. ];
  8926. if ( n11 !== undefined ) {
  8927. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8928. }
  8929. }
  8930. /**
  8931. * Sets the elements of the matrix.The arguments are supposed to be
  8932. * in row-major order.
  8933. *
  8934. * @param {number} [n11] - 1-1 matrix element.
  8935. * @param {number} [n12] - 1-2 matrix element.
  8936. * @param {number} [n13] - 1-3 matrix element.
  8937. * @param {number} [n14] - 1-4 matrix element.
  8938. * @param {number} [n21] - 2-1 matrix element.
  8939. * @param {number} [n22] - 2-2 matrix element.
  8940. * @param {number} [n23] - 2-3 matrix element.
  8941. * @param {number} [n24] - 2-4 matrix element.
  8942. * @param {number} [n31] - 3-1 matrix element.
  8943. * @param {number} [n32] - 3-2 matrix element.
  8944. * @param {number} [n33] - 3-3 matrix element.
  8945. * @param {number} [n34] - 3-4 matrix element.
  8946. * @param {number} [n41] - 4-1 matrix element.
  8947. * @param {number} [n42] - 4-2 matrix element.
  8948. * @param {number} [n43] - 4-3 matrix element.
  8949. * @param {number} [n44] - 4-4 matrix element.
  8950. * @return {Matrix4} A reference to this matrix.
  8951. */
  8952. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8953. const te = this.elements;
  8954. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8955. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8956. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8957. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8958. return this;
  8959. }
  8960. /**
  8961. * Sets this matrix to the 4x4 identity matrix.
  8962. *
  8963. * @return {Matrix4} A reference to this matrix.
  8964. */
  8965. identity() {
  8966. this.set(
  8967. 1, 0, 0, 0,
  8968. 0, 1, 0, 0,
  8969. 0, 0, 1, 0,
  8970. 0, 0, 0, 1
  8971. );
  8972. return this;
  8973. }
  8974. /**
  8975. * Returns a matrix with copied values from this instance.
  8976. *
  8977. * @return {Matrix4} A clone of this instance.
  8978. */
  8979. clone() {
  8980. return new Matrix4().fromArray( this.elements );
  8981. }
  8982. /**
  8983. * Copies the values of the given matrix to this instance.
  8984. *
  8985. * @param {Matrix4} m - The matrix to copy.
  8986. * @return {Matrix4} A reference to this matrix.
  8987. */
  8988. copy( m ) {
  8989. const te = this.elements;
  8990. const me = m.elements;
  8991. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8992. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8993. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8994. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8995. return this;
  8996. }
  8997. /**
  8998. * Copies the translation component of the given matrix
  8999. * into this matrix's translation component.
  9000. *
  9001. * @param {Matrix4} m - The matrix to copy the translation component.
  9002. * @return {Matrix4} A reference to this matrix.
  9003. */
  9004. copyPosition( m ) {
  9005. const te = this.elements, me = m.elements;
  9006. te[ 12 ] = me[ 12 ];
  9007. te[ 13 ] = me[ 13 ];
  9008. te[ 14 ] = me[ 14 ];
  9009. return this;
  9010. }
  9011. /**
  9012. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  9013. *
  9014. * @param {Matrix3} m - The 3x3 matrix.
  9015. * @return {Matrix4} A reference to this matrix.
  9016. */
  9017. setFromMatrix3( m ) {
  9018. const me = m.elements;
  9019. this.set(
  9020. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  9021. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  9022. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  9023. 0, 0, 0, 1
  9024. );
  9025. return this;
  9026. }
  9027. /**
  9028. * Extracts the basis of this matrix into the three axis vectors provided.
  9029. *
  9030. * @param {Vector3} xAxis - The basis's x axis.
  9031. * @param {Vector3} yAxis - The basis's y axis.
  9032. * @param {Vector3} zAxis - The basis's z axis.
  9033. * @return {Matrix4} A reference to this matrix.
  9034. */
  9035. extractBasis( xAxis, yAxis, zAxis ) {
  9036. if ( this.determinant() === 0 ) {
  9037. xAxis.set( 1, 0, 0 );
  9038. yAxis.set( 0, 1, 0 );
  9039. zAxis.set( 0, 0, 1 );
  9040. return this;
  9041. }
  9042. xAxis.setFromMatrixColumn( this, 0 );
  9043. yAxis.setFromMatrixColumn( this, 1 );
  9044. zAxis.setFromMatrixColumn( this, 2 );
  9045. return this;
  9046. }
  9047. /**
  9048. * Sets the given basis vectors to this matrix.
  9049. *
  9050. * @param {Vector3} xAxis - The basis's x axis.
  9051. * @param {Vector3} yAxis - The basis's y axis.
  9052. * @param {Vector3} zAxis - The basis's z axis.
  9053. * @return {Matrix4} A reference to this matrix.
  9054. */
  9055. makeBasis( xAxis, yAxis, zAxis ) {
  9056. this.set(
  9057. xAxis.x, yAxis.x, zAxis.x, 0,
  9058. xAxis.y, yAxis.y, zAxis.y, 0,
  9059. xAxis.z, yAxis.z, zAxis.z, 0,
  9060. 0, 0, 0, 1
  9061. );
  9062. return this;
  9063. }
  9064. /**
  9065. * Extracts the rotation component of the given matrix
  9066. * into this matrix's rotation component.
  9067. *
  9068. * Note: This method does not support reflection matrices.
  9069. *
  9070. * @param {Matrix4} m - The matrix.
  9071. * @return {Matrix4} A reference to this matrix.
  9072. */
  9073. extractRotation( m ) {
  9074. if ( m.determinant() === 0 ) {
  9075. return this.identity();
  9076. }
  9077. const te = this.elements;
  9078. const me = m.elements;
  9079. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  9080. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  9081. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  9082. te[ 0 ] = me[ 0 ] * scaleX;
  9083. te[ 1 ] = me[ 1 ] * scaleX;
  9084. te[ 2 ] = me[ 2 ] * scaleX;
  9085. te[ 3 ] = 0;
  9086. te[ 4 ] = me[ 4 ] * scaleY;
  9087. te[ 5 ] = me[ 5 ] * scaleY;
  9088. te[ 6 ] = me[ 6 ] * scaleY;
  9089. te[ 7 ] = 0;
  9090. te[ 8 ] = me[ 8 ] * scaleZ;
  9091. te[ 9 ] = me[ 9 ] * scaleZ;
  9092. te[ 10 ] = me[ 10 ] * scaleZ;
  9093. te[ 11 ] = 0;
  9094. te[ 12 ] = 0;
  9095. te[ 13 ] = 0;
  9096. te[ 14 ] = 0;
  9097. te[ 15 ] = 1;
  9098. return this;
  9099. }
  9100. /**
  9101. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  9102. * the rotation specified by the given Euler angles. The rest of
  9103. * the matrix is set to the identity. Depending on the {@link Euler#order},
  9104. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  9105. * for a complete list.
  9106. *
  9107. * @param {Euler} euler - The Euler angles.
  9108. * @return {Matrix4} A reference to this matrix.
  9109. */
  9110. makeRotationFromEuler( euler ) {
  9111. const te = this.elements;
  9112. const x = euler.x, y = euler.y, z = euler.z;
  9113. const a = Math.cos( x ), b = Math.sin( x );
  9114. const c = Math.cos( y ), d = Math.sin( y );
  9115. const e = Math.cos( z ), f = Math.sin( z );
  9116. if ( euler.order === 'XYZ' ) {
  9117. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9118. te[ 0 ] = c * e;
  9119. te[ 4 ] = - c * f;
  9120. te[ 8 ] = d;
  9121. te[ 1 ] = af + be * d;
  9122. te[ 5 ] = ae - bf * d;
  9123. te[ 9 ] = - b * c;
  9124. te[ 2 ] = bf - ae * d;
  9125. te[ 6 ] = be + af * d;
  9126. te[ 10 ] = a * c;
  9127. } else if ( euler.order === 'YXZ' ) {
  9128. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9129. te[ 0 ] = ce + df * b;
  9130. te[ 4 ] = de * b - cf;
  9131. te[ 8 ] = a * d;
  9132. te[ 1 ] = a * f;
  9133. te[ 5 ] = a * e;
  9134. te[ 9 ] = - b;
  9135. te[ 2 ] = cf * b - de;
  9136. te[ 6 ] = df + ce * b;
  9137. te[ 10 ] = a * c;
  9138. } else if ( euler.order === 'ZXY' ) {
  9139. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9140. te[ 0 ] = ce - df * b;
  9141. te[ 4 ] = - a * f;
  9142. te[ 8 ] = de + cf * b;
  9143. te[ 1 ] = cf + de * b;
  9144. te[ 5 ] = a * e;
  9145. te[ 9 ] = df - ce * b;
  9146. te[ 2 ] = - a * d;
  9147. te[ 6 ] = b;
  9148. te[ 10 ] = a * c;
  9149. } else if ( euler.order === 'ZYX' ) {
  9150. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9151. te[ 0 ] = c * e;
  9152. te[ 4 ] = be * d - af;
  9153. te[ 8 ] = ae * d + bf;
  9154. te[ 1 ] = c * f;
  9155. te[ 5 ] = bf * d + ae;
  9156. te[ 9 ] = af * d - be;
  9157. te[ 2 ] = - d;
  9158. te[ 6 ] = b * c;
  9159. te[ 10 ] = a * c;
  9160. } else if ( euler.order === 'YZX' ) {
  9161. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9162. te[ 0 ] = c * e;
  9163. te[ 4 ] = bd - ac * f;
  9164. te[ 8 ] = bc * f + ad;
  9165. te[ 1 ] = f;
  9166. te[ 5 ] = a * e;
  9167. te[ 9 ] = - b * e;
  9168. te[ 2 ] = - d * e;
  9169. te[ 6 ] = ad * f + bc;
  9170. te[ 10 ] = ac - bd * f;
  9171. } else if ( euler.order === 'XZY' ) {
  9172. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9173. te[ 0 ] = c * e;
  9174. te[ 4 ] = - f;
  9175. te[ 8 ] = d * e;
  9176. te[ 1 ] = ac * f + bd;
  9177. te[ 5 ] = a * e;
  9178. te[ 9 ] = ad * f - bc;
  9179. te[ 2 ] = bc * f - ad;
  9180. te[ 6 ] = b * e;
  9181. te[ 10 ] = bd * f + ac;
  9182. }
  9183. // bottom row
  9184. te[ 3 ] = 0;
  9185. te[ 7 ] = 0;
  9186. te[ 11 ] = 0;
  9187. // last column
  9188. te[ 12 ] = 0;
  9189. te[ 13 ] = 0;
  9190. te[ 14 ] = 0;
  9191. te[ 15 ] = 1;
  9192. return this;
  9193. }
  9194. /**
  9195. * Sets the rotation component of this matrix to the rotation specified by
  9196. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9197. * The rest of the matrix is set to the identity.
  9198. *
  9199. * @param {Quaternion} q - The Quaternion.
  9200. * @return {Matrix4} A reference to this matrix.
  9201. */
  9202. makeRotationFromQuaternion( q ) {
  9203. return this.compose( _zero, q, _one );
  9204. }
  9205. /**
  9206. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9207. * `target`, and oriented by the up-direction.
  9208. *
  9209. * @param {Vector3} eye - The eye vector.
  9210. * @param {Vector3} target - The target vector.
  9211. * @param {Vector3} up - The up vector.
  9212. * @return {Matrix4} A reference to this matrix.
  9213. */
  9214. lookAt( eye, target, up ) {
  9215. const te = this.elements;
  9216. _z.subVectors( eye, target );
  9217. if ( _z.lengthSq() === 0 ) {
  9218. // eye and target are in the same position
  9219. _z.z = 1;
  9220. }
  9221. _z.normalize();
  9222. _x.crossVectors( up, _z );
  9223. if ( _x.lengthSq() === 0 ) {
  9224. // up and z are parallel
  9225. if ( Math.abs( up.z ) === 1 ) {
  9226. _z.x += 0.0001;
  9227. } else {
  9228. _z.z += 0.0001;
  9229. }
  9230. _z.normalize();
  9231. _x.crossVectors( up, _z );
  9232. }
  9233. _x.normalize();
  9234. _y.crossVectors( _z, _x );
  9235. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9236. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9237. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9238. return this;
  9239. }
  9240. /**
  9241. * Post-multiplies this matrix by the given 4x4 matrix.
  9242. *
  9243. * @param {Matrix4} m - The matrix to multiply with.
  9244. * @return {Matrix4} A reference to this matrix.
  9245. */
  9246. multiply( m ) {
  9247. return this.multiplyMatrices( this, m );
  9248. }
  9249. /**
  9250. * Pre-multiplies this matrix by the given 4x4 matrix.
  9251. *
  9252. * @param {Matrix4} m - The matrix to multiply with.
  9253. * @return {Matrix4} A reference to this matrix.
  9254. */
  9255. premultiply( m ) {
  9256. return this.multiplyMatrices( m, this );
  9257. }
  9258. /**
  9259. * Multiples the given 4x4 matrices and stores the result
  9260. * in this matrix.
  9261. *
  9262. * @param {Matrix4} a - The first matrix.
  9263. * @param {Matrix4} b - The second matrix.
  9264. * @return {Matrix4} A reference to this matrix.
  9265. */
  9266. multiplyMatrices( a, b ) {
  9267. const ae = a.elements;
  9268. const be = b.elements;
  9269. const te = this.elements;
  9270. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9271. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9272. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9273. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9274. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9275. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9276. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9277. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9278. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9279. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9280. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9281. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9282. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9283. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9284. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9285. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9286. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9287. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9288. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9289. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9290. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9291. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9292. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9293. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9294. return this;
  9295. }
  9296. /**
  9297. * Multiplies every component of the matrix by the given scalar.
  9298. *
  9299. * @param {number} s - The scalar.
  9300. * @return {Matrix4} A reference to this matrix.
  9301. */
  9302. multiplyScalar( s ) {
  9303. const te = this.elements;
  9304. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9305. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9306. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9307. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9308. return this;
  9309. }
  9310. /**
  9311. * Computes and returns the determinant of this matrix.
  9312. *
  9313. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9314. *
  9315. * @return {number} The determinant.
  9316. */
  9317. determinant() {
  9318. const te = this.elements;
  9319. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9320. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9321. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9322. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9323. const t11 = n23 * n34 - n24 * n33;
  9324. const t12 = n22 * n34 - n24 * n32;
  9325. const t13 = n22 * n33 - n23 * n32;
  9326. const t21 = n21 * n34 - n24 * n31;
  9327. const t22 = n21 * n33 - n23 * n31;
  9328. const t23 = n21 * n32 - n22 * n31;
  9329. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9330. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9331. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9332. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9333. }
  9334. /**
  9335. * Transposes this matrix in place.
  9336. *
  9337. * @return {Matrix4} A reference to this matrix.
  9338. */
  9339. transpose() {
  9340. const te = this.elements;
  9341. let tmp;
  9342. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9343. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9344. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9345. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9346. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9347. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9348. return this;
  9349. }
  9350. /**
  9351. * Sets the position component for this matrix from the given vector,
  9352. * without affecting the rest of the matrix.
  9353. *
  9354. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9355. * @param {number} y - The y component of the vector.
  9356. * @param {number} z - The z component of the vector.
  9357. * @return {Matrix4} A reference to this matrix.
  9358. */
  9359. setPosition( x, y, z ) {
  9360. const te = this.elements;
  9361. if ( x.isVector3 ) {
  9362. te[ 12 ] = x.x;
  9363. te[ 13 ] = x.y;
  9364. te[ 14 ] = x.z;
  9365. } else {
  9366. te[ 12 ] = x;
  9367. te[ 13 ] = y;
  9368. te[ 14 ] = z;
  9369. }
  9370. return this;
  9371. }
  9372. /**
  9373. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9374. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9375. * a zero matrix instead.
  9376. *
  9377. * @return {Matrix4} A reference to this matrix.
  9378. */
  9379. invert() {
  9380. // based on https://github.com/toji/gl-matrix
  9381. const te = this.elements,
  9382. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9383. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9384. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9385. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9386. t1 = n11 * n22 - n21 * n12,
  9387. t2 = n11 * n32 - n31 * n12,
  9388. t3 = n11 * n42 - n41 * n12,
  9389. t4 = n21 * n32 - n31 * n22,
  9390. t5 = n21 * n42 - n41 * n22,
  9391. t6 = n31 * n42 - n41 * n32,
  9392. t7 = n13 * n24 - n23 * n14,
  9393. t8 = n13 * n34 - n33 * n14,
  9394. t9 = n13 * n44 - n43 * n14,
  9395. t10 = n23 * n34 - n33 * n24,
  9396. t11 = n23 * n44 - n43 * n24,
  9397. t12 = n33 * n44 - n43 * n34;
  9398. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  9399. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9400. const detInv = 1 / det;
  9401. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  9402. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  9403. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  9404. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  9405. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  9406. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  9407. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  9408. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  9409. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  9410. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  9411. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  9412. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  9413. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  9414. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  9415. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  9416. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  9417. return this;
  9418. }
  9419. /**
  9420. * Multiplies the columns of this matrix by the given vector.
  9421. *
  9422. * @param {Vector3} v - The scale vector.
  9423. * @return {Matrix4} A reference to this matrix.
  9424. */
  9425. scale( v ) {
  9426. const te = this.elements;
  9427. const x = v.x, y = v.y, z = v.z;
  9428. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9429. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9430. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9431. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9432. return this;
  9433. }
  9434. /**
  9435. * Gets the maximum scale value of the three axes.
  9436. *
  9437. * @return {number} The maximum scale.
  9438. */
  9439. getMaxScaleOnAxis() {
  9440. const te = this.elements;
  9441. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9442. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9443. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9444. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9445. }
  9446. /**
  9447. * Sets this matrix as a translation transform from the given vector.
  9448. *
  9449. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9450. * @param {number} y - The amount to translate in the Y axis.
  9451. * @param {number} z - The amount to translate in the z axis.
  9452. * @return {Matrix4} A reference to this matrix.
  9453. */
  9454. makeTranslation( x, y, z ) {
  9455. if ( x.isVector3 ) {
  9456. this.set(
  9457. 1, 0, 0, x.x,
  9458. 0, 1, 0, x.y,
  9459. 0, 0, 1, x.z,
  9460. 0, 0, 0, 1
  9461. );
  9462. } else {
  9463. this.set(
  9464. 1, 0, 0, x,
  9465. 0, 1, 0, y,
  9466. 0, 0, 1, z,
  9467. 0, 0, 0, 1
  9468. );
  9469. }
  9470. return this;
  9471. }
  9472. /**
  9473. * Sets this matrix as a rotational transformation around the X axis by
  9474. * the given angle.
  9475. *
  9476. * @param {number} theta - The rotation in radians.
  9477. * @return {Matrix4} A reference to this matrix.
  9478. */
  9479. makeRotationX( theta ) {
  9480. const c = Math.cos( theta ), s = Math.sin( theta );
  9481. this.set(
  9482. 1, 0, 0, 0,
  9483. 0, c, - s, 0,
  9484. 0, s, c, 0,
  9485. 0, 0, 0, 1
  9486. );
  9487. return this;
  9488. }
  9489. /**
  9490. * Sets this matrix as a rotational transformation around the Y axis by
  9491. * the given angle.
  9492. *
  9493. * @param {number} theta - The rotation in radians.
  9494. * @return {Matrix4} A reference to this matrix.
  9495. */
  9496. makeRotationY( theta ) {
  9497. const c = Math.cos( theta ), s = Math.sin( theta );
  9498. this.set(
  9499. c, 0, s, 0,
  9500. 0, 1, 0, 0,
  9501. - s, 0, c, 0,
  9502. 0, 0, 0, 1
  9503. );
  9504. return this;
  9505. }
  9506. /**
  9507. * Sets this matrix as a rotational transformation around the Z axis by
  9508. * the given angle.
  9509. *
  9510. * @param {number} theta - The rotation in radians.
  9511. * @return {Matrix4} A reference to this matrix.
  9512. */
  9513. makeRotationZ( theta ) {
  9514. const c = Math.cos( theta ), s = Math.sin( theta );
  9515. this.set(
  9516. c, - s, 0, 0,
  9517. s, c, 0, 0,
  9518. 0, 0, 1, 0,
  9519. 0, 0, 0, 1
  9520. );
  9521. return this;
  9522. }
  9523. /**
  9524. * Sets this matrix as a rotational transformation around the given axis by
  9525. * the given angle.
  9526. *
  9527. * This is a somewhat controversial but mathematically sound alternative to
  9528. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9529. *
  9530. * @param {Vector3} axis - The normalized rotation axis.
  9531. * @param {number} angle - The rotation in radians.
  9532. * @return {Matrix4} A reference to this matrix.
  9533. */
  9534. makeRotationAxis( axis, angle ) {
  9535. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9536. const c = Math.cos( angle );
  9537. const s = Math.sin( angle );
  9538. const t = 1 - c;
  9539. const x = axis.x, y = axis.y, z = axis.z;
  9540. const tx = t * x, ty = t * y;
  9541. this.set(
  9542. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9543. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9544. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9545. 0, 0, 0, 1
  9546. );
  9547. return this;
  9548. }
  9549. /**
  9550. * Sets this matrix as a scale transformation.
  9551. *
  9552. * @param {number} x - The amount to scale in the X axis.
  9553. * @param {number} y - The amount to scale in the Y axis.
  9554. * @param {number} z - The amount to scale in the Z axis.
  9555. * @return {Matrix4} A reference to this matrix.
  9556. */
  9557. makeScale( x, y, z ) {
  9558. this.set(
  9559. x, 0, 0, 0,
  9560. 0, y, 0, 0,
  9561. 0, 0, z, 0,
  9562. 0, 0, 0, 1
  9563. );
  9564. return this;
  9565. }
  9566. /**
  9567. * Sets this matrix as a shear transformation.
  9568. *
  9569. * @param {number} xy - The amount to shear X by Y.
  9570. * @param {number} xz - The amount to shear X by Z.
  9571. * @param {number} yx - The amount to shear Y by X.
  9572. * @param {number} yz - The amount to shear Y by Z.
  9573. * @param {number} zx - The amount to shear Z by X.
  9574. * @param {number} zy - The amount to shear Z by Y.
  9575. * @return {Matrix4} A reference to this matrix.
  9576. */
  9577. makeShear( xy, xz, yx, yz, zx, zy ) {
  9578. this.set(
  9579. 1, yx, zx, 0,
  9580. xy, 1, zy, 0,
  9581. xz, yz, 1, 0,
  9582. 0, 0, 0, 1
  9583. );
  9584. return this;
  9585. }
  9586. /**
  9587. * Sets this matrix to the transformation composed of the given position,
  9588. * rotation (Quaternion) and scale.
  9589. *
  9590. * @param {Vector3} position - The position vector.
  9591. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9592. * @param {Vector3} scale - The scale vector.
  9593. * @return {Matrix4} A reference to this matrix.
  9594. */
  9595. compose( position, quaternion, scale ) {
  9596. const te = this.elements;
  9597. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9598. const x2 = x + x, y2 = y + y, z2 = z + z;
  9599. const xx = x * x2, xy = x * y2, xz = x * z2;
  9600. const yy = y * y2, yz = y * z2, zz = z * z2;
  9601. const wx = w * x2, wy = w * y2, wz = w * z2;
  9602. const sx = scale.x, sy = scale.y, sz = scale.z;
  9603. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9604. te[ 1 ] = ( xy + wz ) * sx;
  9605. te[ 2 ] = ( xz - wy ) * sx;
  9606. te[ 3 ] = 0;
  9607. te[ 4 ] = ( xy - wz ) * sy;
  9608. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9609. te[ 6 ] = ( yz + wx ) * sy;
  9610. te[ 7 ] = 0;
  9611. te[ 8 ] = ( xz + wy ) * sz;
  9612. te[ 9 ] = ( yz - wx ) * sz;
  9613. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9614. te[ 11 ] = 0;
  9615. te[ 12 ] = position.x;
  9616. te[ 13 ] = position.y;
  9617. te[ 14 ] = position.z;
  9618. te[ 15 ] = 1;
  9619. return this;
  9620. }
  9621. /**
  9622. * Decomposes this matrix into its position, rotation and scale components
  9623. * and provides the result in the given objects.
  9624. *
  9625. * Note: Not all matrices are decomposable in this way. For example, if an
  9626. * object has a non-uniformly scaled parent, then the object's world matrix
  9627. * may not be decomposable, and this method may not be appropriate.
  9628. *
  9629. * @param {Vector3} position - The position vector.
  9630. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9631. * @param {Vector3} scale - The scale vector.
  9632. * @return {Matrix4} A reference to this matrix.
  9633. */
  9634. decompose( position, quaternion, scale ) {
  9635. const te = this.elements;
  9636. position.x = te[ 12 ];
  9637. position.y = te[ 13 ];
  9638. position.z = te[ 14 ];
  9639. const det = this.determinant();
  9640. if ( det === 0 ) {
  9641. scale.set( 1, 1, 1 );
  9642. quaternion.identity();
  9643. return this;
  9644. }
  9645. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9646. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9647. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9648. // if determinant is negative, we need to invert one scale
  9649. if ( det < 0 ) sx = - sx;
  9650. // scale the rotation part
  9651. _m1$4.copy( this );
  9652. const invSX = 1 / sx;
  9653. const invSY = 1 / sy;
  9654. const invSZ = 1 / sz;
  9655. _m1$4.elements[ 0 ] *= invSX;
  9656. _m1$4.elements[ 1 ] *= invSX;
  9657. _m1$4.elements[ 2 ] *= invSX;
  9658. _m1$4.elements[ 4 ] *= invSY;
  9659. _m1$4.elements[ 5 ] *= invSY;
  9660. _m1$4.elements[ 6 ] *= invSY;
  9661. _m1$4.elements[ 8 ] *= invSZ;
  9662. _m1$4.elements[ 9 ] *= invSZ;
  9663. _m1$4.elements[ 10 ] *= invSZ;
  9664. quaternion.setFromRotationMatrix( _m1$4 );
  9665. scale.x = sx;
  9666. scale.y = sy;
  9667. scale.z = sz;
  9668. return this;
  9669. }
  9670. /**
  9671. * Creates a perspective projection matrix. This is used internally by
  9672. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9673. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9674. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9675. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9676. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9677. * @param {number} near - The distance from the camera to the near plane.
  9678. * @param {number} far - The distance from the camera to the far plane.
  9679. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9680. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9681. * @return {Matrix4} A reference to this matrix.
  9682. */
  9683. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9684. const te = this.elements;
  9685. const x = 2 * near / ( right - left );
  9686. const y = 2 * near / ( top - bottom );
  9687. const a = ( right + left ) / ( right - left );
  9688. const b = ( top + bottom ) / ( top - bottom );
  9689. let c, d;
  9690. if ( reversedDepth ) {
  9691. c = near / ( far - near );
  9692. d = ( far * near ) / ( far - near );
  9693. } else {
  9694. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9695. c = - ( far + near ) / ( far - near );
  9696. d = ( -2 * far * near ) / ( far - near );
  9697. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9698. c = - far / ( far - near );
  9699. d = ( - far * near ) / ( far - near );
  9700. } else {
  9701. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9702. }
  9703. }
  9704. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9705. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9706. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9707. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9708. return this;
  9709. }
  9710. /**
  9711. * Creates a orthographic projection matrix. This is used internally by
  9712. * {@link OrthographicCamera#updateProjectionMatrix}.
  9713. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9714. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9715. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9716. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9717. * @param {number} near - The distance from the camera to the near plane.
  9718. * @param {number} far - The distance from the camera to the far plane.
  9719. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9720. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9721. * @return {Matrix4} A reference to this matrix.
  9722. */
  9723. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9724. const te = this.elements;
  9725. const x = 2 / ( right - left );
  9726. const y = 2 / ( top - bottom );
  9727. const a = - ( right + left ) / ( right - left );
  9728. const b = - ( top + bottom ) / ( top - bottom );
  9729. let c, d;
  9730. if ( reversedDepth ) {
  9731. c = 1 / ( far - near );
  9732. d = far / ( far - near );
  9733. } else {
  9734. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9735. c = -2 / ( far - near );
  9736. d = - ( far + near ) / ( far - near );
  9737. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9738. c = -1 / ( far - near );
  9739. d = - near / ( far - near );
  9740. } else {
  9741. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9742. }
  9743. }
  9744. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9745. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9746. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9747. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9748. return this;
  9749. }
  9750. /**
  9751. * Returns `true` if this matrix is equal with the given one.
  9752. *
  9753. * @param {Matrix4} matrix - The matrix to test for equality.
  9754. * @return {boolean} Whether this matrix is equal with the given one.
  9755. */
  9756. equals( matrix ) {
  9757. const te = this.elements;
  9758. const me = matrix.elements;
  9759. for ( let i = 0; i < 16; i ++ ) {
  9760. if ( te[ i ] !== me[ i ] ) return false;
  9761. }
  9762. return true;
  9763. }
  9764. /**
  9765. * Sets the elements of the matrix from the given array.
  9766. *
  9767. * @param {Array<number>} array - The matrix elements in column-major order.
  9768. * @param {number} [offset=0] - Index of the first element in the array.
  9769. * @return {Matrix4} A reference to this matrix.
  9770. */
  9771. fromArray( array, offset = 0 ) {
  9772. for ( let i = 0; i < 16; i ++ ) {
  9773. this.elements[ i ] = array[ i + offset ];
  9774. }
  9775. return this;
  9776. }
  9777. /**
  9778. * Writes the elements of this matrix to the given array. If no array is provided,
  9779. * the method returns a new instance.
  9780. *
  9781. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9782. * @param {number} [offset=0] - Index of the first element in the array.
  9783. * @return {Array<number>} The matrix elements in column-major order.
  9784. */
  9785. toArray( array = [], offset = 0 ) {
  9786. const te = this.elements;
  9787. array[ offset ] = te[ 0 ];
  9788. array[ offset + 1 ] = te[ 1 ];
  9789. array[ offset + 2 ] = te[ 2 ];
  9790. array[ offset + 3 ] = te[ 3 ];
  9791. array[ offset + 4 ] = te[ 4 ];
  9792. array[ offset + 5 ] = te[ 5 ];
  9793. array[ offset + 6 ] = te[ 6 ];
  9794. array[ offset + 7 ] = te[ 7 ];
  9795. array[ offset + 8 ] = te[ 8 ];
  9796. array[ offset + 9 ] = te[ 9 ];
  9797. array[ offset + 10 ] = te[ 10 ];
  9798. array[ offset + 11 ] = te[ 11 ];
  9799. array[ offset + 12 ] = te[ 12 ];
  9800. array[ offset + 13 ] = te[ 13 ];
  9801. array[ offset + 14 ] = te[ 14 ];
  9802. array[ offset + 15 ] = te[ 15 ];
  9803. return array;
  9804. }
  9805. }
  9806. const _v1$5 = /*@__PURE__*/ new Vector3();
  9807. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9808. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9809. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9810. const _x = /*@__PURE__*/ new Vector3();
  9811. const _y = /*@__PURE__*/ new Vector3();
  9812. const _z = /*@__PURE__*/ new Vector3();
  9813. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9814. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  9815. /**
  9816. * A class representing Euler angles.
  9817. *
  9818. * Euler angles describe a rotational transformation by rotating an object on
  9819. * its various axes in specified amounts per axis, and a specified axis
  9820. * order.
  9821. *
  9822. * Iterating through an instance will yield its components (x, y, z,
  9823. * order) in the corresponding order.
  9824. *
  9825. * ```js
  9826. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9827. * const b = new THREE.Vector3( 1, 0, 1 );
  9828. * b.applyEuler(a);
  9829. * ```
  9830. */
  9831. class Euler {
  9832. /**
  9833. * Constructs a new euler instance.
  9834. *
  9835. * @param {number} [x=0] - The angle of the x axis in radians.
  9836. * @param {number} [y=0] - The angle of the y axis in radians.
  9837. * @param {number} [z=0] - The angle of the z axis in radians.
  9838. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9839. */
  9840. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9841. /**
  9842. * This flag can be used for type testing.
  9843. *
  9844. * @type {boolean}
  9845. * @readonly
  9846. * @default true
  9847. */
  9848. this.isEuler = true;
  9849. this._x = x;
  9850. this._y = y;
  9851. this._z = z;
  9852. this._order = order;
  9853. }
  9854. /**
  9855. * The angle of the x axis in radians.
  9856. *
  9857. * @type {number}
  9858. * @default 0
  9859. */
  9860. get x() {
  9861. return this._x;
  9862. }
  9863. set x( value ) {
  9864. this._x = value;
  9865. this._onChangeCallback();
  9866. }
  9867. /**
  9868. * The angle of the y axis in radians.
  9869. *
  9870. * @type {number}
  9871. * @default 0
  9872. */
  9873. get y() {
  9874. return this._y;
  9875. }
  9876. set y( value ) {
  9877. this._y = value;
  9878. this._onChangeCallback();
  9879. }
  9880. /**
  9881. * The angle of the z axis in radians.
  9882. *
  9883. * @type {number}
  9884. * @default 0
  9885. */
  9886. get z() {
  9887. return this._z;
  9888. }
  9889. set z( value ) {
  9890. this._z = value;
  9891. this._onChangeCallback();
  9892. }
  9893. /**
  9894. * A string representing the order that the rotations are applied.
  9895. *
  9896. * @type {string}
  9897. * @default 'XYZ'
  9898. */
  9899. get order() {
  9900. return this._order;
  9901. }
  9902. set order( value ) {
  9903. this._order = value;
  9904. this._onChangeCallback();
  9905. }
  9906. /**
  9907. * Sets the Euler components.
  9908. *
  9909. * @param {number} x - The angle of the x axis in radians.
  9910. * @param {number} y - The angle of the y axis in radians.
  9911. * @param {number} z - The angle of the z axis in radians.
  9912. * @param {string} [order] - A string representing the order that the rotations are applied.
  9913. * @return {Euler} A reference to this Euler instance.
  9914. */
  9915. set( x, y, z, order = this._order ) {
  9916. this._x = x;
  9917. this._y = y;
  9918. this._z = z;
  9919. this._order = order;
  9920. this._onChangeCallback();
  9921. return this;
  9922. }
  9923. /**
  9924. * Returns a new Euler instance with copied values from this instance.
  9925. *
  9926. * @return {Euler} A clone of this instance.
  9927. */
  9928. clone() {
  9929. return new this.constructor( this._x, this._y, this._z, this._order );
  9930. }
  9931. /**
  9932. * Copies the values of the given Euler instance to this instance.
  9933. *
  9934. * @param {Euler} euler - The Euler instance to copy.
  9935. * @return {Euler} A reference to this Euler instance.
  9936. */
  9937. copy( euler ) {
  9938. this._x = euler._x;
  9939. this._y = euler._y;
  9940. this._z = euler._z;
  9941. this._order = euler._order;
  9942. this._onChangeCallback();
  9943. return this;
  9944. }
  9945. /**
  9946. * Sets the angles of this Euler instance from a pure rotation matrix.
  9947. *
  9948. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9949. * @param {string} [order] - A string representing the order that the rotations are applied.
  9950. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9951. * @return {Euler} A reference to this Euler instance.
  9952. */
  9953. setFromRotationMatrix( m, order = this._order, update = true ) {
  9954. const te = m.elements;
  9955. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9956. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9957. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9958. switch ( order ) {
  9959. case 'XYZ':
  9960. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9961. if ( Math.abs( m13 ) < 0.9999999 ) {
  9962. this._x = Math.atan2( - m23, m33 );
  9963. this._z = Math.atan2( - m12, m11 );
  9964. } else {
  9965. this._x = Math.atan2( m32, m22 );
  9966. this._z = 0;
  9967. }
  9968. break;
  9969. case 'YXZ':
  9970. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9971. if ( Math.abs( m23 ) < 0.9999999 ) {
  9972. this._y = Math.atan2( m13, m33 );
  9973. this._z = Math.atan2( m21, m22 );
  9974. } else {
  9975. this._y = Math.atan2( - m31, m11 );
  9976. this._z = 0;
  9977. }
  9978. break;
  9979. case 'ZXY':
  9980. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9981. if ( Math.abs( m32 ) < 0.9999999 ) {
  9982. this._y = Math.atan2( - m31, m33 );
  9983. this._z = Math.atan2( - m12, m22 );
  9984. } else {
  9985. this._y = 0;
  9986. this._z = Math.atan2( m21, m11 );
  9987. }
  9988. break;
  9989. case 'ZYX':
  9990. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9991. if ( Math.abs( m31 ) < 0.9999999 ) {
  9992. this._x = Math.atan2( m32, m33 );
  9993. this._z = Math.atan2( m21, m11 );
  9994. } else {
  9995. this._x = 0;
  9996. this._z = Math.atan2( - m12, m22 );
  9997. }
  9998. break;
  9999. case 'YZX':
  10000. this._z = Math.asin( clamp( m21, -1, 1 ) );
  10001. if ( Math.abs( m21 ) < 0.9999999 ) {
  10002. this._x = Math.atan2( - m23, m22 );
  10003. this._y = Math.atan2( - m31, m11 );
  10004. } else {
  10005. this._x = 0;
  10006. this._y = Math.atan2( m13, m33 );
  10007. }
  10008. break;
  10009. case 'XZY':
  10010. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  10011. if ( Math.abs( m12 ) < 0.9999999 ) {
  10012. this._x = Math.atan2( m32, m22 );
  10013. this._y = Math.atan2( m13, m11 );
  10014. } else {
  10015. this._x = Math.atan2( - m23, m33 );
  10016. this._y = 0;
  10017. }
  10018. break;
  10019. default:
  10020. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  10021. }
  10022. this._order = order;
  10023. if ( update === true ) this._onChangeCallback();
  10024. return this;
  10025. }
  10026. /**
  10027. * Sets the angles of this Euler instance from a normalized quaternion.
  10028. *
  10029. * @param {Quaternion} q - A normalized Quaternion.
  10030. * @param {string} [order] - A string representing the order that the rotations are applied.
  10031. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  10032. * @return {Euler} A reference to this Euler instance.
  10033. */
  10034. setFromQuaternion( q, order, update ) {
  10035. _matrix$2.makeRotationFromQuaternion( q );
  10036. return this.setFromRotationMatrix( _matrix$2, order, update );
  10037. }
  10038. /**
  10039. * Sets the angles of this Euler instance from the given vector.
  10040. *
  10041. * @param {Vector3} v - The vector.
  10042. * @param {string} [order] - A string representing the order that the rotations are applied.
  10043. * @return {Euler} A reference to this Euler instance.
  10044. */
  10045. setFromVector3( v, order = this._order ) {
  10046. return this.set( v.x, v.y, v.z, order );
  10047. }
  10048. /**
  10049. * Resets the euler angle with a new order by creating a quaternion from this
  10050. * euler angle and then setting this euler angle with the quaternion and the
  10051. * new order.
  10052. *
  10053. * Warning: This discards revolution information.
  10054. *
  10055. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  10056. * @return {Euler} A reference to this Euler instance.
  10057. */
  10058. reorder( newOrder ) {
  10059. _quaternion$4.setFromEuler( this );
  10060. return this.setFromQuaternion( _quaternion$4, newOrder );
  10061. }
  10062. /**
  10063. * Returns `true` if this Euler instance is equal with the given one.
  10064. *
  10065. * @param {Euler} euler - The Euler instance to test for equality.
  10066. * @return {boolean} Whether this Euler instance is equal with the given one.
  10067. */
  10068. equals( euler ) {
  10069. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10070. }
  10071. /**
  10072. * Sets this Euler instance's components to values from the given array. The first three
  10073. * entries of the array are assign to the x,y and z components. An optional fourth entry
  10074. * defines the Euler order.
  10075. *
  10076. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  10077. * @return {Euler} A reference to this Euler instance.
  10078. */
  10079. fromArray( array ) {
  10080. this._x = array[ 0 ];
  10081. this._y = array[ 1 ];
  10082. this._z = array[ 2 ];
  10083. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10084. this._onChangeCallback();
  10085. return this;
  10086. }
  10087. /**
  10088. * Writes the components of this Euler instance to the given array. If no array is provided,
  10089. * the method returns a new instance.
  10090. *
  10091. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  10092. * @param {number} [offset=0] - Index of the first element in the array.
  10093. * @return {Array<number,number,number,string>} The Euler components.
  10094. */
  10095. toArray( array = [], offset = 0 ) {
  10096. array[ offset ] = this._x;
  10097. array[ offset + 1 ] = this._y;
  10098. array[ offset + 2 ] = this._z;
  10099. array[ offset + 3 ] = this._order;
  10100. return array;
  10101. }
  10102. _onChange( callback ) {
  10103. this._onChangeCallback = callback;
  10104. return this;
  10105. }
  10106. _onChangeCallback() {}
  10107. *[ Symbol.iterator ]() {
  10108. yield this._x;
  10109. yield this._y;
  10110. yield this._z;
  10111. yield this._order;
  10112. }
  10113. }
  10114. /**
  10115. * The default Euler angle order.
  10116. *
  10117. * @static
  10118. * @type {string}
  10119. * @default 'XYZ'
  10120. */
  10121. Euler.DEFAULT_ORDER = 'XYZ';
  10122. /**
  10123. * A layers object assigns an 3D object to 1 or more of 32
  10124. * layers numbered `0` to `31` - internally the layers are stored as a
  10125. * bit mask], and by default all 3D objects are a member of layer `0`.
  10126. *
  10127. * This can be used to control visibility - an object must share a layer with
  10128. * a camera to be visible when that camera's view is
  10129. * rendered.
  10130. *
  10131. * All classes that inherit from {@link Object3D} have an `layers` property which
  10132. * is an instance of this class.
  10133. */
  10134. class Layers {
  10135. /**
  10136. * Constructs a new layers instance, with membership
  10137. * initially set to layer `0`.
  10138. */
  10139. constructor() {
  10140. /**
  10141. * A bit mask storing which of the 32 layers this layers object is currently
  10142. * a member of.
  10143. *
  10144. * @type {number}
  10145. */
  10146. this.mask = 1 | 0;
  10147. }
  10148. /**
  10149. * Sets membership to the given layer, and remove membership all other layers.
  10150. *
  10151. * @param {number} layer - The layer to set.
  10152. */
  10153. set( layer ) {
  10154. this.mask = ( 1 << layer | 0 ) >>> 0;
  10155. }
  10156. /**
  10157. * Adds membership of the given layer.
  10158. *
  10159. * @param {number} layer - The layer to enable.
  10160. */
  10161. enable( layer ) {
  10162. this.mask |= 1 << layer | 0;
  10163. }
  10164. /**
  10165. * Adds membership to all layers.
  10166. */
  10167. enableAll() {
  10168. this.mask = 0xffffffff | 0;
  10169. }
  10170. /**
  10171. * Toggles the membership of the given layer.
  10172. *
  10173. * @param {number} layer - The layer to toggle.
  10174. */
  10175. toggle( layer ) {
  10176. this.mask ^= 1 << layer | 0;
  10177. }
  10178. /**
  10179. * Removes membership of the given layer.
  10180. *
  10181. * @param {number} layer - The layer to enable.
  10182. */
  10183. disable( layer ) {
  10184. this.mask &= ~ ( 1 << layer | 0 );
  10185. }
  10186. /**
  10187. * Removes the membership from all layers.
  10188. */
  10189. disableAll() {
  10190. this.mask = 0;
  10191. }
  10192. /**
  10193. * Returns `true` if this and the given layers object have at least one
  10194. * layer in common.
  10195. *
  10196. * @param {Layers} layers - The layers to test.
  10197. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10198. */
  10199. test( layers ) {
  10200. return ( this.mask & layers.mask ) !== 0;
  10201. }
  10202. /**
  10203. * Returns `true` if the given layer is enabled.
  10204. *
  10205. * @param {number} layer - The layer to test.
  10206. * @return {boolean } Whether the given layer is enabled or not.
  10207. */
  10208. isEnabled( layer ) {
  10209. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10210. }
  10211. }
  10212. let _object3DId = 0;
  10213. const _v1$4 = /*@__PURE__*/ new Vector3();
  10214. const _q1 = /*@__PURE__*/ new Quaternion();
  10215. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10216. const _target = /*@__PURE__*/ new Vector3();
  10217. const _position$4 = /*@__PURE__*/ new Vector3();
  10218. const _scale$3 = /*@__PURE__*/ new Vector3();
  10219. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  10220. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10221. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10222. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10223. /**
  10224. * Fires when the object has been added to its parent object.
  10225. *
  10226. * @event Object3D#added
  10227. * @type {Object}
  10228. */
  10229. const _addedEvent = { type: 'added' };
  10230. /**
  10231. * Fires when the object has been removed from its parent object.
  10232. *
  10233. * @event Object3D#removed
  10234. * @type {Object}
  10235. */
  10236. const _removedEvent = { type: 'removed' };
  10237. /**
  10238. * Fires when a new child object has been added.
  10239. *
  10240. * @event Object3D#childadded
  10241. * @type {Object}
  10242. */
  10243. const _childaddedEvent = { type: 'childadded', child: null };
  10244. /**
  10245. * Fires when a child object has been removed.
  10246. *
  10247. * @event Object3D#childremoved
  10248. * @type {Object}
  10249. */
  10250. const _childremovedEvent = { type: 'childremoved', child: null };
  10251. /**
  10252. * This is the base class for most objects in three.js and provides a set of
  10253. * properties and methods for manipulating objects in 3D space.
  10254. *
  10255. * @augments EventDispatcher
  10256. */
  10257. class Object3D extends EventDispatcher {
  10258. /**
  10259. * Constructs a new 3D object.
  10260. */
  10261. constructor() {
  10262. super();
  10263. /**
  10264. * This flag can be used for type testing.
  10265. *
  10266. * @type {boolean}
  10267. * @readonly
  10268. * @default true
  10269. */
  10270. this.isObject3D = true;
  10271. /**
  10272. * The ID of the 3D object.
  10273. *
  10274. * @name Object3D#id
  10275. * @type {number}
  10276. * @readonly
  10277. */
  10278. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10279. /**
  10280. * The UUID of the 3D object.
  10281. *
  10282. * @type {string}
  10283. * @readonly
  10284. */
  10285. this.uuid = generateUUID();
  10286. /**
  10287. * The name of the 3D object.
  10288. *
  10289. * @type {string}
  10290. */
  10291. this.name = '';
  10292. /**
  10293. * The type property is used for detecting the object type
  10294. * in context of serialization/deserialization.
  10295. *
  10296. * @type {string}
  10297. * @readonly
  10298. */
  10299. this.type = 'Object3D';
  10300. /**
  10301. * A reference to the parent object.
  10302. *
  10303. * @type {?Object3D}
  10304. * @default null
  10305. */
  10306. this.parent = null;
  10307. /**
  10308. * An array holding the child 3D objects of this instance.
  10309. *
  10310. * @type {Array<Object3D>}
  10311. */
  10312. this.children = [];
  10313. /**
  10314. * Defines the `up` direction of the 3D object which influences
  10315. * the orientation via methods like {@link Object3D#lookAt}.
  10316. *
  10317. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10318. *
  10319. * @type {Vector3}
  10320. */
  10321. this.up = Object3D.DEFAULT_UP.clone();
  10322. const position = new Vector3();
  10323. const rotation = new Euler();
  10324. const quaternion = new Quaternion();
  10325. const scale = new Vector3( 1, 1, 1 );
  10326. function onRotationChange() {
  10327. quaternion.setFromEuler( rotation, false );
  10328. }
  10329. function onQuaternionChange() {
  10330. rotation.setFromQuaternion( quaternion, undefined, false );
  10331. }
  10332. rotation._onChange( onRotationChange );
  10333. quaternion._onChange( onQuaternionChange );
  10334. Object.defineProperties( this, {
  10335. /**
  10336. * Represents the object's local position.
  10337. *
  10338. * @name Object3D#position
  10339. * @type {Vector3}
  10340. * @default (0,0,0)
  10341. */
  10342. position: {
  10343. configurable: true,
  10344. enumerable: true,
  10345. value: position
  10346. },
  10347. /**
  10348. * Represents the object's local rotation as Euler angles, in radians.
  10349. *
  10350. * @name Object3D#rotation
  10351. * @type {Euler}
  10352. * @default (0,0,0)
  10353. */
  10354. rotation: {
  10355. configurable: true,
  10356. enumerable: true,
  10357. value: rotation
  10358. },
  10359. /**
  10360. * Represents the object's local rotation as Quaternions.
  10361. *
  10362. * @name Object3D#quaternion
  10363. * @type {Quaternion}
  10364. */
  10365. quaternion: {
  10366. configurable: true,
  10367. enumerable: true,
  10368. value: quaternion
  10369. },
  10370. /**
  10371. * Represents the object's local scale.
  10372. *
  10373. * @name Object3D#scale
  10374. * @type {Vector3}
  10375. * @default (1,1,1)
  10376. */
  10377. scale: {
  10378. configurable: true,
  10379. enumerable: true,
  10380. value: scale
  10381. },
  10382. /**
  10383. * Represents the object's model-view matrix.
  10384. *
  10385. * @name Object3D#modelViewMatrix
  10386. * @type {Matrix4}
  10387. */
  10388. modelViewMatrix: {
  10389. value: new Matrix4()
  10390. },
  10391. /**
  10392. * Represents the object's normal matrix.
  10393. *
  10394. * @name Object3D#normalMatrix
  10395. * @type {Matrix3}
  10396. */
  10397. normalMatrix: {
  10398. value: new Matrix3()
  10399. }
  10400. } );
  10401. /**
  10402. * Represents the object's transformation matrix in local space.
  10403. *
  10404. * @type {Matrix4}
  10405. */
  10406. this.matrix = new Matrix4();
  10407. /**
  10408. * Represents the object's transformation matrix in world space.
  10409. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10410. *
  10411. * @type {Matrix4}
  10412. */
  10413. this.matrixWorld = new Matrix4();
  10414. /**
  10415. * When set to `true`, the engine automatically computes the local matrix from position,
  10416. * rotation and scale every frame.
  10417. *
  10418. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10419. *
  10420. * @type {boolean}
  10421. * @default true
  10422. */
  10423. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10424. /**
  10425. * When set to `true`, the engine automatically computes the world matrix from the current local
  10426. * matrix and the object's transformation hierarchy.
  10427. *
  10428. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10429. *
  10430. * @type {boolean}
  10431. * @default true
  10432. */
  10433. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10434. /**
  10435. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10436. * to `false`.
  10437. *
  10438. * @type {boolean}
  10439. * @default false
  10440. */
  10441. this.matrixWorldNeedsUpdate = false;
  10442. /**
  10443. * The layer membership of the 3D object. The 3D object is only visible if it has
  10444. * at least one layer in common with the camera in use. This property can also be
  10445. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10446. *
  10447. * @type {Layers}
  10448. */
  10449. this.layers = new Layers();
  10450. /**
  10451. * When set to `true`, the 3D object gets rendered.
  10452. *
  10453. * @type {boolean}
  10454. * @default true
  10455. */
  10456. this.visible = true;
  10457. /**
  10458. * When set to `true`, the 3D object gets rendered into shadow maps.
  10459. *
  10460. * @type {boolean}
  10461. * @default false
  10462. */
  10463. this.castShadow = false;
  10464. /**
  10465. * When set to `true`, the 3D object is affected by shadows in the scene.
  10466. *
  10467. * @type {boolean}
  10468. * @default false
  10469. */
  10470. this.receiveShadow = false;
  10471. /**
  10472. * When set to `true`, the 3D object is honored by view frustum culling.
  10473. *
  10474. * @type {boolean}
  10475. * @default true
  10476. */
  10477. this.frustumCulled = true;
  10478. /**
  10479. * This value allows the default rendering order of scene graph objects to be
  10480. * overridden although opaque and transparent objects remain sorted independently.
  10481. * When this property is set for an instance of {@link Group},all descendants
  10482. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10483. * render order.
  10484. *
  10485. * @type {number}
  10486. * @default 0
  10487. */
  10488. this.renderOrder = 0;
  10489. /**
  10490. * An array holding the animation clips of the 3D object.
  10491. *
  10492. * @type {Array<AnimationClip>}
  10493. */
  10494. this.animations = [];
  10495. /**
  10496. * Custom depth material to be used when rendering to the depth map. Can only be used
  10497. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10498. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10499. * material for proper shadows.
  10500. *
  10501. * Only relevant in context of {@link WebGLRenderer}.
  10502. *
  10503. * @type {(Material|undefined)}
  10504. * @default undefined
  10505. */
  10506. this.customDepthMaterial = undefined;
  10507. /**
  10508. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10509. *
  10510. * Only relevant in context of {@link WebGLRenderer}.
  10511. *
  10512. * @type {(Material|undefined)}
  10513. * @default undefined
  10514. */
  10515. this.customDistanceMaterial = undefined;
  10516. /**
  10517. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  10518. * the 3D object is not going to be changed after the initial renderer. This includes
  10519. * geometry and material settings. A static 3D object can be processed by the renderer
  10520. * slightly faster since certain state checks can be bypassed.
  10521. *
  10522. * Only relevant in context of {@link WebGPURenderer}.
  10523. *
  10524. * @type {boolean}
  10525. * @default false
  10526. */
  10527. this.static = false;
  10528. /**
  10529. * An object that can be used to store custom data about the 3D object. It
  10530. * should not hold references to functions as these will not be cloned.
  10531. *
  10532. * @type {Object}
  10533. */
  10534. this.userData = {};
  10535. /**
  10536. * The pivot point for rotation and scale transformations.
  10537. * When set, rotation and scale are applied around this point
  10538. * instead of the object's origin.
  10539. *
  10540. * @type {?Vector3}
  10541. * @default null
  10542. */
  10543. this.pivot = null;
  10544. }
  10545. /**
  10546. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10547. *
  10548. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10549. * @param {Object3D} object - The 3D object.
  10550. * @param {Camera} camera - The camera that is used to render the scene.
  10551. * @param {Camera} shadowCamera - The shadow camera.
  10552. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10553. * @param {Material} depthMaterial - The depth material.
  10554. * @param {Object} group - The geometry group data.
  10555. */
  10556. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10557. /**
  10558. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10559. *
  10560. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10561. * @param {Object3D} object - The 3D object.
  10562. * @param {Camera} camera - The camera that is used to render the scene.
  10563. * @param {Camera} shadowCamera - The shadow camera.
  10564. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10565. * @param {Material} depthMaterial - The depth material.
  10566. * @param {Object} group - The geometry group data.
  10567. */
  10568. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10569. /**
  10570. * A callback that is executed immediately before a 3D object is rendered.
  10571. *
  10572. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10573. * @param {Object3D} object - The 3D object.
  10574. * @param {Camera} camera - The camera that is used to render the scene.
  10575. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10576. * @param {Material} material - The 3D object's material.
  10577. * @param {Object} group - The geometry group data.
  10578. */
  10579. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10580. /**
  10581. * A callback that is executed immediately after a 3D object is rendered.
  10582. *
  10583. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10584. * @param {Object3D} object - The 3D object.
  10585. * @param {Camera} camera - The camera that is used to render the scene.
  10586. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10587. * @param {Material} material - The 3D object's material.
  10588. * @param {Object} group - The geometry group data.
  10589. */
  10590. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10591. /**
  10592. * Applies the given transformation matrix to the object and updates the object's position,
  10593. * rotation and scale.
  10594. *
  10595. * @param {Matrix4} matrix - The transformation matrix.
  10596. */
  10597. applyMatrix4( matrix ) {
  10598. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10599. this.matrix.premultiply( matrix );
  10600. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10601. }
  10602. /**
  10603. * Applies a rotation represented by given the quaternion to the 3D object.
  10604. *
  10605. * @param {Quaternion} q - The quaternion.
  10606. * @return {Object3D} A reference to this instance.
  10607. */
  10608. applyQuaternion( q ) {
  10609. this.quaternion.premultiply( q );
  10610. return this;
  10611. }
  10612. /**
  10613. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10614. *
  10615. * @param {Vector3} axis - The (normalized) axis vector.
  10616. * @param {number} angle - The angle in radians.
  10617. */
  10618. setRotationFromAxisAngle( axis, angle ) {
  10619. // assumes axis is normalized
  10620. this.quaternion.setFromAxisAngle( axis, angle );
  10621. }
  10622. /**
  10623. * Sets the given rotation represented as Euler angles to the 3D object.
  10624. *
  10625. * @param {Euler} euler - The Euler angles.
  10626. */
  10627. setRotationFromEuler( euler ) {
  10628. this.quaternion.setFromEuler( euler, true );
  10629. }
  10630. /**
  10631. * Sets the given rotation represented as rotation matrix to the 3D object.
  10632. *
  10633. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10634. * a pure rotation matrix (i.e, unscaled).
  10635. */
  10636. setRotationFromMatrix( m ) {
  10637. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10638. this.quaternion.setFromRotationMatrix( m );
  10639. }
  10640. /**
  10641. * Sets the given rotation represented as a Quaternion to the 3D object.
  10642. *
  10643. * @param {Quaternion} q - The Quaternion
  10644. */
  10645. setRotationFromQuaternion( q ) {
  10646. // assumes q is normalized
  10647. this.quaternion.copy( q );
  10648. }
  10649. /**
  10650. * Rotates the 3D object along an axis in local space.
  10651. *
  10652. * @param {Vector3} axis - The (normalized) axis vector.
  10653. * @param {number} angle - The angle in radians.
  10654. * @return {Object3D} A reference to this instance.
  10655. */
  10656. rotateOnAxis( axis, angle ) {
  10657. // rotate object on axis in object space
  10658. // axis is assumed to be normalized
  10659. _q1.setFromAxisAngle( axis, angle );
  10660. this.quaternion.multiply( _q1 );
  10661. return this;
  10662. }
  10663. /**
  10664. * Rotates the 3D object along an axis in world space.
  10665. *
  10666. * @param {Vector3} axis - The (normalized) axis vector.
  10667. * @param {number} angle - The angle in radians.
  10668. * @return {Object3D} A reference to this instance.
  10669. */
  10670. rotateOnWorldAxis( axis, angle ) {
  10671. // rotate object on axis in world space
  10672. // axis is assumed to be normalized
  10673. // method assumes no rotated parent
  10674. _q1.setFromAxisAngle( axis, angle );
  10675. this.quaternion.premultiply( _q1 );
  10676. return this;
  10677. }
  10678. /**
  10679. * Rotates the 3D object around its X axis in local space.
  10680. *
  10681. * @param {number} angle - The angle in radians.
  10682. * @return {Object3D} A reference to this instance.
  10683. */
  10684. rotateX( angle ) {
  10685. return this.rotateOnAxis( _xAxis, angle );
  10686. }
  10687. /**
  10688. * Rotates the 3D object around its Y axis in local space.
  10689. *
  10690. * @param {number} angle - The angle in radians.
  10691. * @return {Object3D} A reference to this instance.
  10692. */
  10693. rotateY( angle ) {
  10694. return this.rotateOnAxis( _yAxis, angle );
  10695. }
  10696. /**
  10697. * Rotates the 3D object around its Z axis in local space.
  10698. *
  10699. * @param {number} angle - The angle in radians.
  10700. * @return {Object3D} A reference to this instance.
  10701. */
  10702. rotateZ( angle ) {
  10703. return this.rotateOnAxis( _zAxis, angle );
  10704. }
  10705. /**
  10706. * Translate the 3D object by a distance along the given axis in local space.
  10707. *
  10708. * @param {Vector3} axis - The (normalized) axis vector.
  10709. * @param {number} distance - The distance in world units.
  10710. * @return {Object3D} A reference to this instance.
  10711. */
  10712. translateOnAxis( axis, distance ) {
  10713. // translate object by distance along axis in object space
  10714. // axis is assumed to be normalized
  10715. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10716. this.position.add( _v1$4.multiplyScalar( distance ) );
  10717. return this;
  10718. }
  10719. /**
  10720. * Translate the 3D object by a distance along its X-axis in local space.
  10721. *
  10722. * @param {number} distance - The distance in world units.
  10723. * @return {Object3D} A reference to this instance.
  10724. */
  10725. translateX( distance ) {
  10726. return this.translateOnAxis( _xAxis, distance );
  10727. }
  10728. /**
  10729. * Translate the 3D object by a distance along its Y-axis in local space.
  10730. *
  10731. * @param {number} distance - The distance in world units.
  10732. * @return {Object3D} A reference to this instance.
  10733. */
  10734. translateY( distance ) {
  10735. return this.translateOnAxis( _yAxis, distance );
  10736. }
  10737. /**
  10738. * Translate the 3D object by a distance along its Z-axis in local space.
  10739. *
  10740. * @param {number} distance - The distance in world units.
  10741. * @return {Object3D} A reference to this instance.
  10742. */
  10743. translateZ( distance ) {
  10744. return this.translateOnAxis( _zAxis, distance );
  10745. }
  10746. /**
  10747. * Converts the given vector from this 3D object's local space to world space.
  10748. *
  10749. * @param {Vector3} vector - The vector to convert.
  10750. * @return {Vector3} The converted vector.
  10751. */
  10752. localToWorld( vector ) {
  10753. this.updateWorldMatrix( true, false );
  10754. return vector.applyMatrix4( this.matrixWorld );
  10755. }
  10756. /**
  10757. * Converts the given vector from this 3D object's world space to local space.
  10758. *
  10759. * @param {Vector3} vector - The vector to convert.
  10760. * @return {Vector3} The converted vector.
  10761. */
  10762. worldToLocal( vector ) {
  10763. this.updateWorldMatrix( true, false );
  10764. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10765. }
  10766. /**
  10767. * Rotates the object to face a point in world space.
  10768. *
  10769. * This method does not support objects having non-uniformly-scaled parent(s).
  10770. *
  10771. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10772. * @param {number} [y] - The y coordinate in world space.
  10773. * @param {number} [z] - The z coordinate in world space.
  10774. */
  10775. lookAt( x, y, z ) {
  10776. // This method does not support objects having non-uniformly-scaled parent(s)
  10777. if ( x.isVector3 ) {
  10778. _target.copy( x );
  10779. } else {
  10780. _target.set( x, y, z );
  10781. }
  10782. const parent = this.parent;
  10783. this.updateWorldMatrix( true, false );
  10784. _position$4.setFromMatrixPosition( this.matrixWorld );
  10785. if ( this.isCamera || this.isLight ) {
  10786. _m1$3.lookAt( _position$4, _target, this.up );
  10787. } else {
  10788. _m1$3.lookAt( _target, _position$4, this.up );
  10789. }
  10790. this.quaternion.setFromRotationMatrix( _m1$3 );
  10791. if ( parent ) {
  10792. _m1$3.extractRotation( parent.matrixWorld );
  10793. _q1.setFromRotationMatrix( _m1$3 );
  10794. this.quaternion.premultiply( _q1.invert() );
  10795. }
  10796. }
  10797. /**
  10798. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10799. * objects may be added. Any current parent on an object passed in here will be
  10800. * removed, since an object can have at most one parent.
  10801. *
  10802. * @fires Object3D#added
  10803. * @fires Object3D#childadded
  10804. * @param {Object3D} object - The 3D object to add.
  10805. * @return {Object3D} A reference to this instance.
  10806. */
  10807. add( object ) {
  10808. if ( arguments.length > 1 ) {
  10809. for ( let i = 0; i < arguments.length; i ++ ) {
  10810. this.add( arguments[ i ] );
  10811. }
  10812. return this;
  10813. }
  10814. if ( object === this ) {
  10815. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10816. return this;
  10817. }
  10818. if ( object && object.isObject3D ) {
  10819. object.removeFromParent();
  10820. object.parent = this;
  10821. this.children.push( object );
  10822. object.dispatchEvent( _addedEvent );
  10823. _childaddedEvent.child = object;
  10824. this.dispatchEvent( _childaddedEvent );
  10825. _childaddedEvent.child = null;
  10826. } else {
  10827. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10828. }
  10829. return this;
  10830. }
  10831. /**
  10832. * Removes the given 3D object as child from this 3D object.
  10833. * An arbitrary number of objects may be removed.
  10834. *
  10835. * @fires Object3D#removed
  10836. * @fires Object3D#childremoved
  10837. * @param {Object3D} object - The 3D object to remove.
  10838. * @return {Object3D} A reference to this instance.
  10839. */
  10840. remove( object ) {
  10841. if ( arguments.length > 1 ) {
  10842. for ( let i = 0; i < arguments.length; i ++ ) {
  10843. this.remove( arguments[ i ] );
  10844. }
  10845. return this;
  10846. }
  10847. const index = this.children.indexOf( object );
  10848. if ( index !== -1 ) {
  10849. object.parent = null;
  10850. this.children.splice( index, 1 );
  10851. object.dispatchEvent( _removedEvent );
  10852. _childremovedEvent.child = object;
  10853. this.dispatchEvent( _childremovedEvent );
  10854. _childremovedEvent.child = null;
  10855. }
  10856. return this;
  10857. }
  10858. /**
  10859. * Removes this 3D object from its current parent.
  10860. *
  10861. * @fires Object3D#removed
  10862. * @fires Object3D#childremoved
  10863. * @return {Object3D} A reference to this instance.
  10864. */
  10865. removeFromParent() {
  10866. const parent = this.parent;
  10867. if ( parent !== null ) {
  10868. parent.remove( this );
  10869. }
  10870. return this;
  10871. }
  10872. /**
  10873. * Removes all child objects.
  10874. *
  10875. * @fires Object3D#removed
  10876. * @fires Object3D#childremoved
  10877. * @return {Object3D} A reference to this instance.
  10878. */
  10879. clear() {
  10880. return this.remove( ... this.children );
  10881. }
  10882. /**
  10883. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10884. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10885. *
  10886. * @fires Object3D#added
  10887. * @fires Object3D#childadded
  10888. * @param {Object3D} object - The 3D object to attach.
  10889. * @return {Object3D} A reference to this instance.
  10890. */
  10891. attach( object ) {
  10892. // adds object as a child of this, while maintaining the object's world transform
  10893. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10894. this.updateWorldMatrix( true, false );
  10895. _m1$3.copy( this.matrixWorld ).invert();
  10896. if ( object.parent !== null ) {
  10897. object.parent.updateWorldMatrix( true, false );
  10898. _m1$3.multiply( object.parent.matrixWorld );
  10899. }
  10900. object.applyMatrix4( _m1$3 );
  10901. object.removeFromParent();
  10902. object.parent = this;
  10903. this.children.push( object );
  10904. object.updateWorldMatrix( false, true );
  10905. object.dispatchEvent( _addedEvent );
  10906. _childaddedEvent.child = object;
  10907. this.dispatchEvent( _childaddedEvent );
  10908. _childaddedEvent.child = null;
  10909. return this;
  10910. }
  10911. /**
  10912. * Searches through the 3D object and its children, starting with the 3D object
  10913. * itself, and returns the first with a matching ID.
  10914. *
  10915. * @param {number} id - The id.
  10916. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10917. */
  10918. getObjectById( id ) {
  10919. return this.getObjectByProperty( 'id', id );
  10920. }
  10921. /**
  10922. * Searches through the 3D object and its children, starting with the 3D object
  10923. * itself, and returns the first with a matching name.
  10924. *
  10925. * @param {string} name - The name.
  10926. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10927. */
  10928. getObjectByName( name ) {
  10929. return this.getObjectByProperty( 'name', name );
  10930. }
  10931. /**
  10932. * Searches through the 3D object and its children, starting with the 3D object
  10933. * itself, and returns the first with a matching property value.
  10934. *
  10935. * @param {string} name - The name of the property.
  10936. * @param {any} value - The value.
  10937. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10938. */
  10939. getObjectByProperty( name, value ) {
  10940. if ( this[ name ] === value ) return this;
  10941. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10942. const child = this.children[ i ];
  10943. const object = child.getObjectByProperty( name, value );
  10944. if ( object !== undefined ) {
  10945. return object;
  10946. }
  10947. }
  10948. return undefined;
  10949. }
  10950. /**
  10951. * Searches through the 3D object and its children, starting with the 3D object
  10952. * itself, and returns all 3D objects with a matching property value.
  10953. *
  10954. * @param {string} name - The name of the property.
  10955. * @param {any} value - The value.
  10956. * @param {Array<Object3D>} result - The method stores the result in this array.
  10957. * @return {Array<Object3D>} The found 3D objects.
  10958. */
  10959. getObjectsByProperty( name, value, result = [] ) {
  10960. if ( this[ name ] === value ) result.push( this );
  10961. const children = this.children;
  10962. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10963. children[ i ].getObjectsByProperty( name, value, result );
  10964. }
  10965. return result;
  10966. }
  10967. /**
  10968. * Returns a vector representing the position of the 3D object in world space.
  10969. *
  10970. * @param {Vector3} target - The target vector the result is stored to.
  10971. * @return {Vector3} The 3D object's position in world space.
  10972. */
  10973. getWorldPosition( target ) {
  10974. this.updateWorldMatrix( true, false );
  10975. return target.setFromMatrixPosition( this.matrixWorld );
  10976. }
  10977. /**
  10978. * Returns a Quaternion representing the position of the 3D object in world space.
  10979. *
  10980. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10981. * @return {Quaternion} The 3D object's rotation in world space.
  10982. */
  10983. getWorldQuaternion( target ) {
  10984. this.updateWorldMatrix( true, false );
  10985. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  10986. return target;
  10987. }
  10988. /**
  10989. * Returns a vector representing the scale of the 3D object in world space.
  10990. *
  10991. * @param {Vector3} target - The target vector the result is stored to.
  10992. * @return {Vector3} The 3D object's scale in world space.
  10993. */
  10994. getWorldScale( target ) {
  10995. this.updateWorldMatrix( true, false );
  10996. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  10997. return target;
  10998. }
  10999. /**
  11000. * Returns a vector representing the ("look") direction of the 3D object in world space.
  11001. *
  11002. * @param {Vector3} target - The target vector the result is stored to.
  11003. * @return {Vector3} The 3D object's direction in world space.
  11004. */
  11005. getWorldDirection( target ) {
  11006. this.updateWorldMatrix( true, false );
  11007. const e = this.matrixWorld.elements;
  11008. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  11009. }
  11010. /**
  11011. * Abstract method to get intersections between a casted ray and this
  11012. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  11013. * implement this method in order to use raycasting.
  11014. *
  11015. * @abstract
  11016. * @param {Raycaster} raycaster - The raycaster.
  11017. * @param {Array<Object>} intersects - An array holding the result of the method.
  11018. */
  11019. raycast( /* raycaster, intersects */ ) {}
  11020. /**
  11021. * Executes the callback on this 3D object and all descendants.
  11022. *
  11023. * Note: Modifying the scene graph inside the callback is discouraged.
  11024. *
  11025. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11026. */
  11027. traverse( callback ) {
  11028. callback( this );
  11029. const children = this.children;
  11030. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11031. children[ i ].traverse( callback );
  11032. }
  11033. }
  11034. /**
  11035. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  11036. * Descendants of invisible 3D objects are not traversed.
  11037. *
  11038. * Note: Modifying the scene graph inside the callback is discouraged.
  11039. *
  11040. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11041. */
  11042. traverseVisible( callback ) {
  11043. if ( this.visible === false ) return;
  11044. callback( this );
  11045. const children = this.children;
  11046. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11047. children[ i ].traverseVisible( callback );
  11048. }
  11049. }
  11050. /**
  11051. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  11052. *
  11053. * Note: Modifying the scene graph inside the callback is discouraged.
  11054. *
  11055. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11056. */
  11057. traverseAncestors( callback ) {
  11058. const parent = this.parent;
  11059. if ( parent !== null ) {
  11060. callback( parent );
  11061. parent.traverseAncestors( callback );
  11062. }
  11063. }
  11064. /**
  11065. * Updates the transformation matrix in local space by computing it from the current
  11066. * position, rotation and scale values.
  11067. */
  11068. updateMatrix() {
  11069. this.matrix.compose( this.position, this.quaternion, this.scale );
  11070. const pivot = this.pivot;
  11071. if ( pivot !== null ) {
  11072. const px = pivot.x, py = pivot.y, pz = pivot.z;
  11073. const te = this.matrix.elements;
  11074. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  11075. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  11076. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  11077. }
  11078. this.matrixWorldNeedsUpdate = true;
  11079. }
  11080. /**
  11081. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  11082. *
  11083. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  11084. * local space. The computation of the local and world matrix can be controlled with the
  11085. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  11086. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  11087. *
  11088. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  11089. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  11090. */
  11091. updateMatrixWorld( force ) {
  11092. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11093. if ( this.matrixWorldNeedsUpdate || force ) {
  11094. if ( this.matrixWorldAutoUpdate === true ) {
  11095. if ( this.parent === null ) {
  11096. this.matrixWorld.copy( this.matrix );
  11097. } else {
  11098. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11099. }
  11100. }
  11101. this.matrixWorldNeedsUpdate = false;
  11102. force = true;
  11103. }
  11104. // make sure descendants are updated if required
  11105. const children = this.children;
  11106. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11107. const child = children[ i ];
  11108. child.updateMatrixWorld( force );
  11109. }
  11110. }
  11111. /**
  11112. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  11113. * update of ancestor and descendant nodes.
  11114. *
  11115. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  11116. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  11117. */
  11118. updateWorldMatrix( updateParents, updateChildren ) {
  11119. const parent = this.parent;
  11120. if ( updateParents === true && parent !== null ) {
  11121. parent.updateWorldMatrix( true, false );
  11122. }
  11123. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11124. if ( this.matrixWorldAutoUpdate === true ) {
  11125. if ( this.parent === null ) {
  11126. this.matrixWorld.copy( this.matrix );
  11127. } else {
  11128. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11129. }
  11130. }
  11131. // make sure descendants are updated
  11132. if ( updateChildren === true ) {
  11133. const children = this.children;
  11134. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11135. const child = children[ i ];
  11136. child.updateWorldMatrix( false, true );
  11137. }
  11138. }
  11139. }
  11140. /**
  11141. * Serializes the 3D object into JSON.
  11142. *
  11143. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11144. * @return {Object} A JSON object representing the serialized 3D object.
  11145. * @see {@link ObjectLoader#parse}
  11146. */
  11147. toJSON( meta ) {
  11148. // meta is a string when called from JSON.stringify
  11149. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  11150. const output = {};
  11151. // meta is a hash used to collect geometries, materials.
  11152. // not providing it implies that this is the root object
  11153. // being serialized.
  11154. if ( isRootObject ) {
  11155. // initialize meta obj
  11156. meta = {
  11157. geometries: {},
  11158. materials: {},
  11159. textures: {},
  11160. images: {},
  11161. shapes: {},
  11162. skeletons: {},
  11163. animations: {},
  11164. nodes: {}
  11165. };
  11166. output.metadata = {
  11167. version: 4.7,
  11168. type: 'Object',
  11169. generator: 'Object3D.toJSON'
  11170. };
  11171. }
  11172. // standard Object3D serialization
  11173. const object = {};
  11174. object.uuid = this.uuid;
  11175. object.type = this.type;
  11176. if ( this.name !== '' ) object.name = this.name;
  11177. if ( this.castShadow === true ) object.castShadow = true;
  11178. if ( this.receiveShadow === true ) object.receiveShadow = true;
  11179. if ( this.visible === false ) object.visible = false;
  11180. if ( this.frustumCulled === false ) object.frustumCulled = false;
  11181. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  11182. if ( this.static !== false ) object.static = this.static;
  11183. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  11184. object.layers = this.layers.mask;
  11185. object.matrix = this.matrix.toArray();
  11186. object.up = this.up.toArray();
  11187. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  11188. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  11189. // object specific properties
  11190. if ( this.isInstancedMesh ) {
  11191. object.type = 'InstancedMesh';
  11192. object.count = this.count;
  11193. object.instanceMatrix = this.instanceMatrix.toJSON();
  11194. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11195. }
  11196. if ( this.isBatchedMesh ) {
  11197. object.type = 'BatchedMesh';
  11198. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11199. object.sortObjects = this.sortObjects;
  11200. object.drawRanges = this._drawRanges;
  11201. object.reservedRanges = this._reservedRanges;
  11202. object.geometryInfo = this._geometryInfo.map( info => ( {
  11203. ...info,
  11204. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11205. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11206. } ) );
  11207. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11208. object.availableInstanceIds = this._availableInstanceIds.slice();
  11209. object.availableGeometryIds = this._availableGeometryIds.slice();
  11210. object.nextIndexStart = this._nextIndexStart;
  11211. object.nextVertexStart = this._nextVertexStart;
  11212. object.geometryCount = this._geometryCount;
  11213. object.maxInstanceCount = this._maxInstanceCount;
  11214. object.maxVertexCount = this._maxVertexCount;
  11215. object.maxIndexCount = this._maxIndexCount;
  11216. object.geometryInitialized = this._geometryInitialized;
  11217. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11218. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11219. if ( this._colorsTexture !== null ) {
  11220. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11221. }
  11222. if ( this.boundingSphere !== null ) {
  11223. object.boundingSphere = this.boundingSphere.toJSON();
  11224. }
  11225. if ( this.boundingBox !== null ) {
  11226. object.boundingBox = this.boundingBox.toJSON();
  11227. }
  11228. }
  11229. //
  11230. function serialize( library, element ) {
  11231. if ( library[ element.uuid ] === undefined ) {
  11232. library[ element.uuid ] = element.toJSON( meta );
  11233. }
  11234. return element.uuid;
  11235. }
  11236. if ( this.isScene ) {
  11237. if ( this.background ) {
  11238. if ( this.background.isColor ) {
  11239. object.background = this.background.toJSON();
  11240. } else if ( this.background.isTexture ) {
  11241. object.background = this.background.toJSON( meta ).uuid;
  11242. }
  11243. }
  11244. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11245. object.environment = this.environment.toJSON( meta ).uuid;
  11246. }
  11247. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11248. object.geometry = serialize( meta.geometries, this.geometry );
  11249. const parameters = this.geometry.parameters;
  11250. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11251. const shapes = parameters.shapes;
  11252. if ( Array.isArray( shapes ) ) {
  11253. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11254. const shape = shapes[ i ];
  11255. serialize( meta.shapes, shape );
  11256. }
  11257. } else {
  11258. serialize( meta.shapes, shapes );
  11259. }
  11260. }
  11261. }
  11262. if ( this.isSkinnedMesh ) {
  11263. object.bindMode = this.bindMode;
  11264. object.bindMatrix = this.bindMatrix.toArray();
  11265. if ( this.skeleton !== undefined ) {
  11266. serialize( meta.skeletons, this.skeleton );
  11267. object.skeleton = this.skeleton.uuid;
  11268. }
  11269. }
  11270. if ( this.material !== undefined ) {
  11271. if ( Array.isArray( this.material ) ) {
  11272. const uuids = [];
  11273. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11274. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11275. }
  11276. object.material = uuids;
  11277. } else {
  11278. object.material = serialize( meta.materials, this.material );
  11279. }
  11280. }
  11281. //
  11282. if ( this.children.length > 0 ) {
  11283. object.children = [];
  11284. for ( let i = 0; i < this.children.length; i ++ ) {
  11285. object.children.push( this.children[ i ].toJSON( meta ).object );
  11286. }
  11287. }
  11288. //
  11289. if ( this.animations.length > 0 ) {
  11290. object.animations = [];
  11291. for ( let i = 0; i < this.animations.length; i ++ ) {
  11292. const animation = this.animations[ i ];
  11293. object.animations.push( serialize( meta.animations, animation ) );
  11294. }
  11295. }
  11296. if ( isRootObject ) {
  11297. const geometries = extractFromCache( meta.geometries );
  11298. const materials = extractFromCache( meta.materials );
  11299. const textures = extractFromCache( meta.textures );
  11300. const images = extractFromCache( meta.images );
  11301. const shapes = extractFromCache( meta.shapes );
  11302. const skeletons = extractFromCache( meta.skeletons );
  11303. const animations = extractFromCache( meta.animations );
  11304. const nodes = extractFromCache( meta.nodes );
  11305. if ( geometries.length > 0 ) output.geometries = geometries;
  11306. if ( materials.length > 0 ) output.materials = materials;
  11307. if ( textures.length > 0 ) output.textures = textures;
  11308. if ( images.length > 0 ) output.images = images;
  11309. if ( shapes.length > 0 ) output.shapes = shapes;
  11310. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11311. if ( animations.length > 0 ) output.animations = animations;
  11312. if ( nodes.length > 0 ) output.nodes = nodes;
  11313. }
  11314. output.object = object;
  11315. return output;
  11316. // extract data from the cache hash
  11317. // remove metadata on each item
  11318. // and return as array
  11319. function extractFromCache( cache ) {
  11320. const values = [];
  11321. for ( const key in cache ) {
  11322. const data = cache[ key ];
  11323. delete data.metadata;
  11324. values.push( data );
  11325. }
  11326. return values;
  11327. }
  11328. }
  11329. /**
  11330. * Returns a new 3D object with copied values from this instance.
  11331. *
  11332. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11333. * @return {Object3D} A clone of this instance.
  11334. */
  11335. clone( recursive ) {
  11336. return new this.constructor().copy( this, recursive );
  11337. }
  11338. /**
  11339. * Copies the values of the given 3D object to this instance.
  11340. *
  11341. * @param {Object3D} source - The 3D object to copy.
  11342. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11343. * @return {Object3D} A reference to this instance.
  11344. */
  11345. copy( source, recursive = true ) {
  11346. this.name = source.name;
  11347. this.up.copy( source.up );
  11348. this.position.copy( source.position );
  11349. this.rotation.order = source.rotation.order;
  11350. this.quaternion.copy( source.quaternion );
  11351. this.scale.copy( source.scale );
  11352. if ( source.pivot !== null ) {
  11353. this.pivot = source.pivot.clone();
  11354. }
  11355. this.matrix.copy( source.matrix );
  11356. this.matrixWorld.copy( source.matrixWorld );
  11357. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11358. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11359. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11360. this.layers.mask = source.layers.mask;
  11361. this.visible = source.visible;
  11362. this.castShadow = source.castShadow;
  11363. this.receiveShadow = source.receiveShadow;
  11364. this.frustumCulled = source.frustumCulled;
  11365. this.renderOrder = source.renderOrder;
  11366. this.static = source.static;
  11367. this.animations = source.animations.slice();
  11368. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11369. if ( recursive === true ) {
  11370. for ( let i = 0; i < source.children.length; i ++ ) {
  11371. const child = source.children[ i ];
  11372. this.add( child.clone() );
  11373. }
  11374. }
  11375. return this;
  11376. }
  11377. }
  11378. /**
  11379. * The default up direction for objects, also used as the default
  11380. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11381. *
  11382. * @static
  11383. * @type {Vector3}
  11384. * @default (0,1,0)
  11385. */
  11386. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11387. /**
  11388. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11389. * newly created 3D objects.
  11390. *
  11391. * @static
  11392. * @type {boolean}
  11393. * @default true
  11394. */
  11395. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11396. /**
  11397. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11398. * newly created 3D objects.
  11399. *
  11400. * @static
  11401. * @type {boolean}
  11402. * @default true
  11403. */
  11404. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11405. const _v0$2 = /*@__PURE__*/ new Vector3();
  11406. const _v1$3 = /*@__PURE__*/ new Vector3();
  11407. const _v2$2 = /*@__PURE__*/ new Vector3();
  11408. const _v3$2 = /*@__PURE__*/ new Vector3();
  11409. const _vab = /*@__PURE__*/ new Vector3();
  11410. const _vac = /*@__PURE__*/ new Vector3();
  11411. const _vbc = /*@__PURE__*/ new Vector3();
  11412. const _vap = /*@__PURE__*/ new Vector3();
  11413. const _vbp = /*@__PURE__*/ new Vector3();
  11414. const _vcp = /*@__PURE__*/ new Vector3();
  11415. const _v40 = /*@__PURE__*/ new Vector4();
  11416. const _v41 = /*@__PURE__*/ new Vector4();
  11417. const _v42 = /*@__PURE__*/ new Vector4();
  11418. /**
  11419. * A geometric triangle as defined by three vectors representing its three corners.
  11420. */
  11421. class Triangle {
  11422. /**
  11423. * Constructs a new triangle.
  11424. *
  11425. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11426. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11427. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11428. */
  11429. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11430. /**
  11431. * The first corner of the triangle.
  11432. *
  11433. * @type {Vector3}
  11434. */
  11435. this.a = a;
  11436. /**
  11437. * The second corner of the triangle.
  11438. *
  11439. * @type {Vector3}
  11440. */
  11441. this.b = b;
  11442. /**
  11443. * The third corner of the triangle.
  11444. *
  11445. * @type {Vector3}
  11446. */
  11447. this.c = c;
  11448. }
  11449. /**
  11450. * Computes the normal vector of a triangle.
  11451. *
  11452. * @param {Vector3} a - The first corner of the triangle.
  11453. * @param {Vector3} b - The second corner of the triangle.
  11454. * @param {Vector3} c - The third corner of the triangle.
  11455. * @param {Vector3} target - The target vector that is used to store the method's result.
  11456. * @return {Vector3} The triangle's normal.
  11457. */
  11458. static getNormal( a, b, c, target ) {
  11459. target.subVectors( c, b );
  11460. _v0$2.subVectors( a, b );
  11461. target.cross( _v0$2 );
  11462. const targetLengthSq = target.lengthSq();
  11463. if ( targetLengthSq > 0 ) {
  11464. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11465. }
  11466. return target.set( 0, 0, 0 );
  11467. }
  11468. /**
  11469. * Computes a barycentric coordinates from the given vector.
  11470. * Returns `null` if the triangle is degenerate.
  11471. *
  11472. * @param {Vector3} point - A point in 3D space.
  11473. * @param {Vector3} a - The first corner of the triangle.
  11474. * @param {Vector3} b - The second corner of the triangle.
  11475. * @param {Vector3} c - The third corner of the triangle.
  11476. * @param {Vector3} target - The target vector that is used to store the method's result.
  11477. * @return {?Vector3} The barycentric coordinates for the given point
  11478. */
  11479. static getBarycoord( point, a, b, c, target ) {
  11480. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11481. _v0$2.subVectors( c, a );
  11482. _v1$3.subVectors( b, a );
  11483. _v2$2.subVectors( point, a );
  11484. const dot00 = _v0$2.dot( _v0$2 );
  11485. const dot01 = _v0$2.dot( _v1$3 );
  11486. const dot02 = _v0$2.dot( _v2$2 );
  11487. const dot11 = _v1$3.dot( _v1$3 );
  11488. const dot12 = _v1$3.dot( _v2$2 );
  11489. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11490. // collinear or singular triangle
  11491. if ( denom === 0 ) {
  11492. target.set( 0, 0, 0 );
  11493. return null;
  11494. }
  11495. const invDenom = 1 / denom;
  11496. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11497. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11498. // barycentric coordinates must always sum to 1
  11499. return target.set( 1 - u - v, v, u );
  11500. }
  11501. /**
  11502. * Returns `true` if the given point, when projected onto the plane of the
  11503. * triangle, lies within the triangle.
  11504. *
  11505. * @param {Vector3} point - The point in 3D space to test.
  11506. * @param {Vector3} a - The first corner of the triangle.
  11507. * @param {Vector3} b - The second corner of the triangle.
  11508. * @param {Vector3} c - The third corner of the triangle.
  11509. * @return {boolean} Whether the given point, when projected onto the plane of the
  11510. * triangle, lies within the triangle or not.
  11511. */
  11512. static containsPoint( point, a, b, c ) {
  11513. // if the triangle is degenerate then we can't contain a point
  11514. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11515. return false;
  11516. }
  11517. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11518. }
  11519. /**
  11520. * Computes the value barycentrically interpolated for the given point on the
  11521. * triangle. Returns `null` if the triangle is degenerate.
  11522. *
  11523. * @param {Vector3} point - Position of interpolated point.
  11524. * @param {Vector3} p1 - The first corner of the triangle.
  11525. * @param {Vector3} p2 - The second corner of the triangle.
  11526. * @param {Vector3} p3 - The third corner of the triangle.
  11527. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11528. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11529. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11530. * @param {Vector3} target - The target vector that is used to store the method's result.
  11531. * @return {?Vector3} The interpolated value.
  11532. */
  11533. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11534. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11535. target.x = 0;
  11536. target.y = 0;
  11537. if ( 'z' in target ) target.z = 0;
  11538. if ( 'w' in target ) target.w = 0;
  11539. return null;
  11540. }
  11541. target.setScalar( 0 );
  11542. target.addScaledVector( v1, _v3$2.x );
  11543. target.addScaledVector( v2, _v3$2.y );
  11544. target.addScaledVector( v3, _v3$2.z );
  11545. return target;
  11546. }
  11547. /**
  11548. * Computes the value barycentrically interpolated for the given attribute and indices.
  11549. *
  11550. * @param {BufferAttribute} attr - The attribute to interpolate.
  11551. * @param {number} i1 - Index of first vertex.
  11552. * @param {number} i2 - Index of second vertex.
  11553. * @param {number} i3 - Index of third vertex.
  11554. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11555. * @param {Vector3} target - The target vector that is used to store the method's result.
  11556. * @return {Vector3} The interpolated attribute value.
  11557. */
  11558. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11559. _v40.setScalar( 0 );
  11560. _v41.setScalar( 0 );
  11561. _v42.setScalar( 0 );
  11562. _v40.fromBufferAttribute( attr, i1 );
  11563. _v41.fromBufferAttribute( attr, i2 );
  11564. _v42.fromBufferAttribute( attr, i3 );
  11565. target.setScalar( 0 );
  11566. target.addScaledVector( _v40, barycoord.x );
  11567. target.addScaledVector( _v41, barycoord.y );
  11568. target.addScaledVector( _v42, barycoord.z );
  11569. return target;
  11570. }
  11571. /**
  11572. * Returns `true` if the triangle is oriented towards the given direction.
  11573. *
  11574. * @param {Vector3} a - The first corner of the triangle.
  11575. * @param {Vector3} b - The second corner of the triangle.
  11576. * @param {Vector3} c - The third corner of the triangle.
  11577. * @param {Vector3} direction - The (normalized) direction vector.
  11578. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11579. */
  11580. static isFrontFacing( a, b, c, direction ) {
  11581. _v0$2.subVectors( c, b );
  11582. _v1$3.subVectors( a, b );
  11583. // strictly front facing
  11584. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11585. }
  11586. /**
  11587. * Sets the triangle's vertices by copying the given values.
  11588. *
  11589. * @param {Vector3} a - The first corner of the triangle.
  11590. * @param {Vector3} b - The second corner of the triangle.
  11591. * @param {Vector3} c - The third corner of the triangle.
  11592. * @return {Triangle} A reference to this triangle.
  11593. */
  11594. set( a, b, c ) {
  11595. this.a.copy( a );
  11596. this.b.copy( b );
  11597. this.c.copy( c );
  11598. return this;
  11599. }
  11600. /**
  11601. * Sets the triangle's vertices by copying the given array values.
  11602. *
  11603. * @param {Array<Vector3>} points - An array with 3D points.
  11604. * @param {number} i0 - The array index representing the first corner of the triangle.
  11605. * @param {number} i1 - The array index representing the second corner of the triangle.
  11606. * @param {number} i2 - The array index representing the third corner of the triangle.
  11607. * @return {Triangle} A reference to this triangle.
  11608. */
  11609. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11610. this.a.copy( points[ i0 ] );
  11611. this.b.copy( points[ i1 ] );
  11612. this.c.copy( points[ i2 ] );
  11613. return this;
  11614. }
  11615. /**
  11616. * Sets the triangle's vertices by copying the given attribute values.
  11617. *
  11618. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11619. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11620. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11621. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11622. * @return {Triangle} A reference to this triangle.
  11623. */
  11624. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11625. this.a.fromBufferAttribute( attribute, i0 );
  11626. this.b.fromBufferAttribute( attribute, i1 );
  11627. this.c.fromBufferAttribute( attribute, i2 );
  11628. return this;
  11629. }
  11630. /**
  11631. * Returns a new triangle with copied values from this instance.
  11632. *
  11633. * @return {Triangle} A clone of this instance.
  11634. */
  11635. clone() {
  11636. return new this.constructor().copy( this );
  11637. }
  11638. /**
  11639. * Copies the values of the given triangle to this instance.
  11640. *
  11641. * @param {Triangle} triangle - The triangle to copy.
  11642. * @return {Triangle} A reference to this triangle.
  11643. */
  11644. copy( triangle ) {
  11645. this.a.copy( triangle.a );
  11646. this.b.copy( triangle.b );
  11647. this.c.copy( triangle.c );
  11648. return this;
  11649. }
  11650. /**
  11651. * Computes the area of the triangle.
  11652. *
  11653. * @return {number} The triangle's area.
  11654. */
  11655. getArea() {
  11656. _v0$2.subVectors( this.c, this.b );
  11657. _v1$3.subVectors( this.a, this.b );
  11658. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11659. }
  11660. /**
  11661. * Computes the midpoint of the triangle.
  11662. *
  11663. * @param {Vector3} target - The target vector that is used to store the method's result.
  11664. * @return {Vector3} The triangle's midpoint.
  11665. */
  11666. getMidpoint( target ) {
  11667. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11668. }
  11669. /**
  11670. * Computes the normal of the triangle.
  11671. *
  11672. * @param {Vector3} target - The target vector that is used to store the method's result.
  11673. * @return {Vector3} The triangle's normal.
  11674. */
  11675. getNormal( target ) {
  11676. return Triangle.getNormal( this.a, this.b, this.c, target );
  11677. }
  11678. /**
  11679. * Computes a plane the triangle lies within.
  11680. *
  11681. * @param {Plane} target - The target vector that is used to store the method's result.
  11682. * @return {Plane} The plane the triangle lies within.
  11683. */
  11684. getPlane( target ) {
  11685. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11686. }
  11687. /**
  11688. * Computes a barycentric coordinates from the given vector.
  11689. * Returns `null` if the triangle is degenerate.
  11690. *
  11691. * @param {Vector3} point - A point in 3D space.
  11692. * @param {Vector3} target - The target vector that is used to store the method's result.
  11693. * @return {?Vector3} The barycentric coordinates for the given point
  11694. */
  11695. getBarycoord( point, target ) {
  11696. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11697. }
  11698. /**
  11699. * Computes the value barycentrically interpolated for the given point on the
  11700. * triangle. Returns `null` if the triangle is degenerate.
  11701. *
  11702. * @param {Vector3} point - Position of interpolated point.
  11703. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11704. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11705. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11706. * @param {Vector3} target - The target vector that is used to store the method's result.
  11707. * @return {?Vector3} The interpolated value.
  11708. */
  11709. getInterpolation( point, v1, v2, v3, target ) {
  11710. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11711. }
  11712. /**
  11713. * Returns `true` if the given point, when projected onto the plane of the
  11714. * triangle, lies within the triangle.
  11715. *
  11716. * @param {Vector3} point - The point in 3D space to test.
  11717. * @return {boolean} Whether the given point, when projected onto the plane of the
  11718. * triangle, lies within the triangle or not.
  11719. */
  11720. containsPoint( point ) {
  11721. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11722. }
  11723. /**
  11724. * Returns `true` if the triangle is oriented towards the given direction.
  11725. *
  11726. * @param {Vector3} direction - The (normalized) direction vector.
  11727. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11728. */
  11729. isFrontFacing( direction ) {
  11730. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11731. }
  11732. /**
  11733. * Returns `true` if this triangle intersects with the given box.
  11734. *
  11735. * @param {Box3} box - The box to intersect.
  11736. * @return {boolean} Whether this triangle intersects with the given box or not.
  11737. */
  11738. intersectsBox( box ) {
  11739. return box.intersectsTriangle( this );
  11740. }
  11741. /**
  11742. * Returns the closest point on the triangle to the given point.
  11743. *
  11744. * @param {Vector3} p - The point to compute the closest point for.
  11745. * @param {Vector3} target - The target vector that is used to store the method's result.
  11746. * @return {Vector3} The closest point on the triangle.
  11747. */
  11748. closestPointToPoint( p, target ) {
  11749. const a = this.a, b = this.b, c = this.c;
  11750. let v, w;
  11751. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11752. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11753. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11754. // basically, we're distinguishing which of the voronoi regions of the triangle
  11755. // the point lies in with the minimum amount of redundant computation.
  11756. _vab.subVectors( b, a );
  11757. _vac.subVectors( c, a );
  11758. _vap.subVectors( p, a );
  11759. const d1 = _vab.dot( _vap );
  11760. const d2 = _vac.dot( _vap );
  11761. if ( d1 <= 0 && d2 <= 0 ) {
  11762. // vertex region of A; barycentric coords (1, 0, 0)
  11763. return target.copy( a );
  11764. }
  11765. _vbp.subVectors( p, b );
  11766. const d3 = _vab.dot( _vbp );
  11767. const d4 = _vac.dot( _vbp );
  11768. if ( d3 >= 0 && d4 <= d3 ) {
  11769. // vertex region of B; barycentric coords (0, 1, 0)
  11770. return target.copy( b );
  11771. }
  11772. const vc = d1 * d4 - d3 * d2;
  11773. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11774. v = d1 / ( d1 - d3 );
  11775. // edge region of AB; barycentric coords (1-v, v, 0)
  11776. return target.copy( a ).addScaledVector( _vab, v );
  11777. }
  11778. _vcp.subVectors( p, c );
  11779. const d5 = _vab.dot( _vcp );
  11780. const d6 = _vac.dot( _vcp );
  11781. if ( d6 >= 0 && d5 <= d6 ) {
  11782. // vertex region of C; barycentric coords (0, 0, 1)
  11783. return target.copy( c );
  11784. }
  11785. const vb = d5 * d2 - d1 * d6;
  11786. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11787. w = d2 / ( d2 - d6 );
  11788. // edge region of AC; barycentric coords (1-w, 0, w)
  11789. return target.copy( a ).addScaledVector( _vac, w );
  11790. }
  11791. const va = d3 * d6 - d5 * d4;
  11792. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11793. _vbc.subVectors( c, b );
  11794. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11795. // edge region of BC; barycentric coords (0, 1-w, w)
  11796. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11797. }
  11798. // face region
  11799. const denom = 1 / ( va + vb + vc );
  11800. // u = va * denom
  11801. v = vb * denom;
  11802. w = vc * denom;
  11803. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11804. }
  11805. /**
  11806. * Returns `true` if this triangle is equal with the given one.
  11807. *
  11808. * @param {Triangle} triangle - The triangle to test for equality.
  11809. * @return {boolean} Whether this triangle is equal with the given one.
  11810. */
  11811. equals( triangle ) {
  11812. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11813. }
  11814. }
  11815. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11816. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11817. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11818. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11819. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11820. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11821. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11822. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11823. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11824. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11825. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11826. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11827. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11828. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11829. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11830. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11831. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11832. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11833. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11834. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11835. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11836. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11837. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11838. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11839. const _hslA = { h: 0, s: 0, l: 0 };
  11840. const _hslB = { h: 0, s: 0, l: 0 };
  11841. function hue2rgb( p, q, t ) {
  11842. if ( t < 0 ) t += 1;
  11843. if ( t > 1 ) t -= 1;
  11844. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11845. if ( t < 1 / 2 ) return q;
  11846. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11847. return p;
  11848. }
  11849. /**
  11850. * A Color instance is represented by RGB components in the linear <i>working
  11851. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11852. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11853. * strings) are converted to the working color space automatically.
  11854. *
  11855. * ```js
  11856. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11857. * const color = new THREE.Color().setHex( 0x112233 );
  11858. * ```
  11859. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11860. * ```js
  11861. * // assumed already LinearSRGBColorSpace; no conversion
  11862. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11863. *
  11864. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11865. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11866. * ```
  11867. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11868. * see <i>Color management</i>. Iterating through a Color instance will yield
  11869. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11870. * in any of the following ways:
  11871. * ```js
  11872. * //empty constructor - will default white
  11873. * const color1 = new THREE.Color();
  11874. *
  11875. * //Hexadecimal color (recommended)
  11876. * const color2 = new THREE.Color( 0xff0000 );
  11877. *
  11878. * //RGB string
  11879. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11880. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11881. *
  11882. * //X11 color name - all 140 color names are supported.
  11883. * //Note the lack of CamelCase in the name
  11884. * const color5 = new THREE.Color( 'skyblue' );
  11885. * //HSL string
  11886. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11887. *
  11888. * //Separate RGB values between 0 and 1
  11889. * const color7 = new THREE.Color( 1, 0, 0 );
  11890. * ```
  11891. */
  11892. class Color {
  11893. /**
  11894. * Constructs a new color.
  11895. *
  11896. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11897. * and that method is used throughout the rest of the documentation.
  11898. *
  11899. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11900. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11901. * @param {number} [g] - The green component.
  11902. * @param {number} [b] - The blue component.
  11903. */
  11904. constructor( r, g, b ) {
  11905. /**
  11906. * This flag can be used for type testing.
  11907. *
  11908. * @type {boolean}
  11909. * @readonly
  11910. * @default true
  11911. */
  11912. this.isColor = true;
  11913. /**
  11914. * The red component.
  11915. *
  11916. * @type {number}
  11917. * @default 1
  11918. */
  11919. this.r = 1;
  11920. /**
  11921. * The green component.
  11922. *
  11923. * @type {number}
  11924. * @default 1
  11925. */
  11926. this.g = 1;
  11927. /**
  11928. * The blue component.
  11929. *
  11930. * @type {number}
  11931. * @default 1
  11932. */
  11933. this.b = 1;
  11934. return this.set( r, g, b );
  11935. }
  11936. /**
  11937. * Sets the colors's components from the given values.
  11938. *
  11939. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11940. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11941. * @param {number} [g] - The green component.
  11942. * @param {number} [b] - The blue component.
  11943. * @return {Color} A reference to this color.
  11944. */
  11945. set( r, g, b ) {
  11946. if ( g === undefined && b === undefined ) {
  11947. // r is THREE.Color, hex or string
  11948. const value = r;
  11949. if ( value && value.isColor ) {
  11950. this.copy( value );
  11951. } else if ( typeof value === 'number' ) {
  11952. this.setHex( value );
  11953. } else if ( typeof value === 'string' ) {
  11954. this.setStyle( value );
  11955. }
  11956. } else {
  11957. this.setRGB( r, g, b );
  11958. }
  11959. return this;
  11960. }
  11961. /**
  11962. * Sets the colors's components to the given scalar value.
  11963. *
  11964. * @param {number} scalar - The scalar value.
  11965. * @return {Color} A reference to this color.
  11966. */
  11967. setScalar( scalar ) {
  11968. this.r = scalar;
  11969. this.g = scalar;
  11970. this.b = scalar;
  11971. return this;
  11972. }
  11973. /**
  11974. * Sets this color from a hexadecimal value.
  11975. *
  11976. * @param {number} hex - The hexadecimal value.
  11977. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11978. * @return {Color} A reference to this color.
  11979. */
  11980. setHex( hex, colorSpace = SRGBColorSpace ) {
  11981. hex = Math.floor( hex );
  11982. this.r = ( hex >> 16 & 255 ) / 255;
  11983. this.g = ( hex >> 8 & 255 ) / 255;
  11984. this.b = ( hex & 255 ) / 255;
  11985. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11986. return this;
  11987. }
  11988. /**
  11989. * Sets this color from RGB values.
  11990. *
  11991. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11992. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11993. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11994. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11995. * @return {Color} A reference to this color.
  11996. */
  11997. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11998. this.r = r;
  11999. this.g = g;
  12000. this.b = b;
  12001. ColorManagement.colorSpaceToWorking( this, colorSpace );
  12002. return this;
  12003. }
  12004. /**
  12005. * Sets this color from RGB values.
  12006. *
  12007. * @param {number} h - Hue value between `0.0` and `1.0`.
  12008. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12009. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12010. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12011. * @return {Color} A reference to this color.
  12012. */
  12013. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  12014. // h,s,l ranges are in 0.0 - 1.0
  12015. h = euclideanModulo( h, 1 );
  12016. s = clamp( s, 0, 1 );
  12017. l = clamp( l, 0, 1 );
  12018. if ( s === 0 ) {
  12019. this.r = this.g = this.b = l;
  12020. } else {
  12021. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  12022. const q = ( 2 * l ) - p;
  12023. this.r = hue2rgb( q, p, h + 1 / 3 );
  12024. this.g = hue2rgb( q, p, h );
  12025. this.b = hue2rgb( q, p, h - 1 / 3 );
  12026. }
  12027. ColorManagement.colorSpaceToWorking( this, colorSpace );
  12028. return this;
  12029. }
  12030. /**
  12031. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  12032. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  12033. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  12034. * all 140 color names are supported).
  12035. *
  12036. * @param {string} style - Color as a CSS-style string.
  12037. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12038. * @return {Color} A reference to this color.
  12039. */
  12040. setStyle( style, colorSpace = SRGBColorSpace ) {
  12041. function handleAlpha( string ) {
  12042. if ( string === undefined ) return;
  12043. if ( parseFloat( string ) < 1 ) {
  12044. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  12045. }
  12046. }
  12047. let m;
  12048. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  12049. // rgb / hsl
  12050. let color;
  12051. const name = m[ 1 ];
  12052. const components = m[ 2 ];
  12053. switch ( name ) {
  12054. case 'rgb':
  12055. case 'rgba':
  12056. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12057. // rgb(255,0,0) rgba(255,0,0,0.5)
  12058. handleAlpha( color[ 4 ] );
  12059. return this.setRGB(
  12060. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  12061. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  12062. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  12063. colorSpace
  12064. );
  12065. }
  12066. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12067. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  12068. handleAlpha( color[ 4 ] );
  12069. return this.setRGB(
  12070. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  12071. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  12072. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  12073. colorSpace
  12074. );
  12075. }
  12076. break;
  12077. case 'hsl':
  12078. case 'hsla':
  12079. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12080. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  12081. handleAlpha( color[ 4 ] );
  12082. return this.setHSL(
  12083. parseFloat( color[ 1 ] ) / 360,
  12084. parseFloat( color[ 2 ] ) / 100,
  12085. parseFloat( color[ 3 ] ) / 100,
  12086. colorSpace
  12087. );
  12088. }
  12089. break;
  12090. default:
  12091. warn( 'Color: Unknown color model ' + style );
  12092. }
  12093. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  12094. // hex color
  12095. const hex = m[ 1 ];
  12096. const size = hex.length;
  12097. if ( size === 3 ) {
  12098. // #ff0
  12099. return this.setRGB(
  12100. parseInt( hex.charAt( 0 ), 16 ) / 15,
  12101. parseInt( hex.charAt( 1 ), 16 ) / 15,
  12102. parseInt( hex.charAt( 2 ), 16 ) / 15,
  12103. colorSpace
  12104. );
  12105. } else if ( size === 6 ) {
  12106. // #ff0000
  12107. return this.setHex( parseInt( hex, 16 ), colorSpace );
  12108. } else {
  12109. warn( 'Color: Invalid hex color ' + style );
  12110. }
  12111. } else if ( style && style.length > 0 ) {
  12112. return this.setColorName( style, colorSpace );
  12113. }
  12114. return this;
  12115. }
  12116. /**
  12117. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  12118. * you don't need the other CSS-style formats.
  12119. *
  12120. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  12121. * ```js
  12122. * Color.NAMES.aliceblue // returns 0xF0F8FF
  12123. * ```
  12124. *
  12125. * @param {string} style - The color name.
  12126. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12127. * @return {Color} A reference to this color.
  12128. */
  12129. setColorName( style, colorSpace = SRGBColorSpace ) {
  12130. // color keywords
  12131. const hex = _colorKeywords[ style.toLowerCase() ];
  12132. if ( hex !== undefined ) {
  12133. // red
  12134. this.setHex( hex, colorSpace );
  12135. } else {
  12136. // unknown color
  12137. warn( 'Color: Unknown color ' + style );
  12138. }
  12139. return this;
  12140. }
  12141. /**
  12142. * Returns a new color with copied values from this instance.
  12143. *
  12144. * @return {Color} A clone of this instance.
  12145. */
  12146. clone() {
  12147. return new this.constructor( this.r, this.g, this.b );
  12148. }
  12149. /**
  12150. * Copies the values of the given color to this instance.
  12151. *
  12152. * @param {Color} color - The color to copy.
  12153. * @return {Color} A reference to this color.
  12154. */
  12155. copy( color ) {
  12156. this.r = color.r;
  12157. this.g = color.g;
  12158. this.b = color.b;
  12159. return this;
  12160. }
  12161. /**
  12162. * Copies the given color into this color, and then converts this color from
  12163. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12164. *
  12165. * @param {Color} color - The color to copy/convert.
  12166. * @return {Color} A reference to this color.
  12167. */
  12168. copySRGBToLinear( color ) {
  12169. this.r = SRGBToLinear( color.r );
  12170. this.g = SRGBToLinear( color.g );
  12171. this.b = SRGBToLinear( color.b );
  12172. return this;
  12173. }
  12174. /**
  12175. * Copies the given color into this color, and then converts this color from
  12176. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12177. *
  12178. * @param {Color} color - The color to copy/convert.
  12179. * @return {Color} A reference to this color.
  12180. */
  12181. copyLinearToSRGB( color ) {
  12182. this.r = LinearToSRGB( color.r );
  12183. this.g = LinearToSRGB( color.g );
  12184. this.b = LinearToSRGB( color.b );
  12185. return this;
  12186. }
  12187. /**
  12188. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12189. *
  12190. * @return {Color} A reference to this color.
  12191. */
  12192. convertSRGBToLinear() {
  12193. this.copySRGBToLinear( this );
  12194. return this;
  12195. }
  12196. /**
  12197. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12198. *
  12199. * @return {Color} A reference to this color.
  12200. */
  12201. convertLinearToSRGB() {
  12202. this.copyLinearToSRGB( this );
  12203. return this;
  12204. }
  12205. /**
  12206. * Returns the hexadecimal value of this color.
  12207. *
  12208. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12209. * @return {number} The hexadecimal value.
  12210. */
  12211. getHex( colorSpace = SRGBColorSpace ) {
  12212. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12213. 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 ) );
  12214. }
  12215. /**
  12216. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12217. *
  12218. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12219. * @return {string} The hexadecimal value as a string.
  12220. */
  12221. getHexString( colorSpace = SRGBColorSpace ) {
  12222. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12223. }
  12224. /**
  12225. * Converts the colors RGB values into the HSL format and stores them into the
  12226. * given target object.
  12227. *
  12228. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12229. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12230. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12231. */
  12232. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12233. // h,s,l ranges are in 0.0 - 1.0
  12234. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12235. const r = _color.r, g = _color.g, b = _color.b;
  12236. const max = Math.max( r, g, b );
  12237. const min = Math.min( r, g, b );
  12238. let hue, saturation;
  12239. const lightness = ( min + max ) / 2.0;
  12240. if ( min === max ) {
  12241. hue = 0;
  12242. saturation = 0;
  12243. } else {
  12244. const delta = max - min;
  12245. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12246. switch ( max ) {
  12247. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12248. case g: hue = ( b - r ) / delta + 2; break;
  12249. case b: hue = ( r - g ) / delta + 4; break;
  12250. }
  12251. hue /= 6;
  12252. }
  12253. target.h = hue;
  12254. target.s = saturation;
  12255. target.l = lightness;
  12256. return target;
  12257. }
  12258. /**
  12259. * Returns the RGB values of this color and stores them into the given target object.
  12260. *
  12261. * @param {Color} target - The target color that is used to store the method's result.
  12262. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12263. * @return {Color} The RGB representation of this color.
  12264. */
  12265. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12266. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12267. target.r = _color.r;
  12268. target.g = _color.g;
  12269. target.b = _color.b;
  12270. return target;
  12271. }
  12272. /**
  12273. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12274. *
  12275. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12276. * @return {string} The CSS representation of this color.
  12277. */
  12278. getStyle( colorSpace = SRGBColorSpace ) {
  12279. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12280. const r = _color.r, g = _color.g, b = _color.b;
  12281. if ( colorSpace !== SRGBColorSpace ) {
  12282. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12283. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12284. }
  12285. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12286. }
  12287. /**
  12288. * Adds the given HSL values to this color's values.
  12289. * Internally, this converts the color's RGB values to HSL, adds HSL
  12290. * and then converts the color back to RGB.
  12291. *
  12292. * @param {number} h - Hue value between `0.0` and `1.0`.
  12293. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12294. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12295. * @return {Color} A reference to this color.
  12296. */
  12297. offsetHSL( h, s, l ) {
  12298. this.getHSL( _hslA );
  12299. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12300. }
  12301. /**
  12302. * Adds the RGB values of the given color to the RGB values of this color.
  12303. *
  12304. * @param {Color} color - The color to add.
  12305. * @return {Color} A reference to this color.
  12306. */
  12307. add( color ) {
  12308. this.r += color.r;
  12309. this.g += color.g;
  12310. this.b += color.b;
  12311. return this;
  12312. }
  12313. /**
  12314. * Adds the RGB values of the given colors and stores the result in this instance.
  12315. *
  12316. * @param {Color} color1 - The first color.
  12317. * @param {Color} color2 - The second color.
  12318. * @return {Color} A reference to this color.
  12319. */
  12320. addColors( color1, color2 ) {
  12321. this.r = color1.r + color2.r;
  12322. this.g = color1.g + color2.g;
  12323. this.b = color1.b + color2.b;
  12324. return this;
  12325. }
  12326. /**
  12327. * Adds the given scalar value to the RGB values of this color.
  12328. *
  12329. * @param {number} s - The scalar to add.
  12330. * @return {Color} A reference to this color.
  12331. */
  12332. addScalar( s ) {
  12333. this.r += s;
  12334. this.g += s;
  12335. this.b += s;
  12336. return this;
  12337. }
  12338. /**
  12339. * Subtracts the RGB values of the given color from the RGB values of this color.
  12340. *
  12341. * @param {Color} color - The color to subtract.
  12342. * @return {Color} A reference to this color.
  12343. */
  12344. sub( color ) {
  12345. this.r = Math.max( 0, this.r - color.r );
  12346. this.g = Math.max( 0, this.g - color.g );
  12347. this.b = Math.max( 0, this.b - color.b );
  12348. return this;
  12349. }
  12350. /**
  12351. * Multiplies the RGB values of the given color with the RGB values of this color.
  12352. *
  12353. * @param {Color} color - The color to multiply.
  12354. * @return {Color} A reference to this color.
  12355. */
  12356. multiply( color ) {
  12357. this.r *= color.r;
  12358. this.g *= color.g;
  12359. this.b *= color.b;
  12360. return this;
  12361. }
  12362. /**
  12363. * Multiplies the given scalar value with the RGB values of this color.
  12364. *
  12365. * @param {number} s - The scalar to multiply.
  12366. * @return {Color} A reference to this color.
  12367. */
  12368. multiplyScalar( s ) {
  12369. this.r *= s;
  12370. this.g *= s;
  12371. this.b *= s;
  12372. return this;
  12373. }
  12374. /**
  12375. * Linearly interpolates this color's RGB values toward the RGB values of the
  12376. * given color. The alpha argument can be thought of as the ratio between
  12377. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12378. *
  12379. * @param {Color} color - The color to converge on.
  12380. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12381. * @return {Color} A reference to this color.
  12382. */
  12383. lerp( color, alpha ) {
  12384. this.r += ( color.r - this.r ) * alpha;
  12385. this.g += ( color.g - this.g ) * alpha;
  12386. this.b += ( color.b - this.b ) * alpha;
  12387. return this;
  12388. }
  12389. /**
  12390. * Linearly interpolates between the given colors and stores the result in this instance.
  12391. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12392. * is the first and `1.0` is the second color.
  12393. *
  12394. * @param {Color} color1 - The first color.
  12395. * @param {Color} color2 - The second color.
  12396. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12397. * @return {Color} A reference to this color.
  12398. */
  12399. lerpColors( color1, color2, alpha ) {
  12400. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12401. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12402. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12403. return this;
  12404. }
  12405. /**
  12406. * Linearly interpolates this color's HSL values toward the HSL values of the
  12407. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12408. * from one color to the other, but instead going through all the hues in between
  12409. * those two colors. The alpha argument can be thought of as the ratio between
  12410. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12411. *
  12412. * @param {Color} color - The color to converge on.
  12413. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12414. * @return {Color} A reference to this color.
  12415. */
  12416. lerpHSL( color, alpha ) {
  12417. this.getHSL( _hslA );
  12418. color.getHSL( _hslB );
  12419. const h = lerp( _hslA.h, _hslB.h, alpha );
  12420. const s = lerp( _hslA.s, _hslB.s, alpha );
  12421. const l = lerp( _hslA.l, _hslB.l, alpha );
  12422. this.setHSL( h, s, l );
  12423. return this;
  12424. }
  12425. /**
  12426. * Sets the color's RGB components from the given 3D vector.
  12427. *
  12428. * @param {Vector3} v - The vector to set.
  12429. * @return {Color} A reference to this color.
  12430. */
  12431. setFromVector3( v ) {
  12432. this.r = v.x;
  12433. this.g = v.y;
  12434. this.b = v.z;
  12435. return this;
  12436. }
  12437. /**
  12438. * Transforms this color with the given 3x3 matrix.
  12439. *
  12440. * @param {Matrix3} m - The matrix.
  12441. * @return {Color} A reference to this color.
  12442. */
  12443. applyMatrix3( m ) {
  12444. const r = this.r, g = this.g, b = this.b;
  12445. const e = m.elements;
  12446. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12447. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12448. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12449. return this;
  12450. }
  12451. /**
  12452. * Returns `true` if this color is equal with the given one.
  12453. *
  12454. * @param {Color} c - The color to test for equality.
  12455. * @return {boolean} Whether this bounding color is equal with the given one.
  12456. */
  12457. equals( c ) {
  12458. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12459. }
  12460. /**
  12461. * Sets this color's RGB components from the given array.
  12462. *
  12463. * @param {Array<number>} array - An array holding the RGB values.
  12464. * @param {number} [offset=0] - The offset into the array.
  12465. * @return {Color} A reference to this color.
  12466. */
  12467. fromArray( array, offset = 0 ) {
  12468. this.r = array[ offset ];
  12469. this.g = array[ offset + 1 ];
  12470. this.b = array[ offset + 2 ];
  12471. return this;
  12472. }
  12473. /**
  12474. * Writes the RGB components of this color to the given array. If no array is provided,
  12475. * the method returns a new instance.
  12476. *
  12477. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12478. * @param {number} [offset=0] - Index of the first element in the array.
  12479. * @return {Array<number>} The color components.
  12480. */
  12481. toArray( array = [], offset = 0 ) {
  12482. array[ offset ] = this.r;
  12483. array[ offset + 1 ] = this.g;
  12484. array[ offset + 2 ] = this.b;
  12485. return array;
  12486. }
  12487. /**
  12488. * Sets the components of this color from the given buffer attribute.
  12489. *
  12490. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12491. * @param {number} index - The index into the attribute.
  12492. * @return {Color} A reference to this color.
  12493. */
  12494. fromBufferAttribute( attribute, index ) {
  12495. this.r = attribute.getX( index );
  12496. this.g = attribute.getY( index );
  12497. this.b = attribute.getZ( index );
  12498. return this;
  12499. }
  12500. /**
  12501. * This methods defines the serialization result of this class. Returns the color
  12502. * as a hexadecimal value.
  12503. *
  12504. * @return {number} The hexadecimal value.
  12505. */
  12506. toJSON() {
  12507. return this.getHex();
  12508. }
  12509. *[ Symbol.iterator ]() {
  12510. yield this.r;
  12511. yield this.g;
  12512. yield this.b;
  12513. }
  12514. }
  12515. const _color = /*@__PURE__*/ new Color();
  12516. /**
  12517. * A dictionary with X11 color names.
  12518. *
  12519. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12520. *
  12521. * @static
  12522. * @type {Object}
  12523. */
  12524. Color.NAMES = _colorKeywords;
  12525. let _materialId = 0;
  12526. /**
  12527. * Abstract base class for materials.
  12528. *
  12529. * Materials define the appearance of renderable 3D objects.
  12530. *
  12531. * @abstract
  12532. * @augments EventDispatcher
  12533. */
  12534. class Material extends EventDispatcher {
  12535. /**
  12536. * Constructs a new material.
  12537. */
  12538. constructor() {
  12539. super();
  12540. /**
  12541. * This flag can be used for type testing.
  12542. *
  12543. * @type {boolean}
  12544. * @readonly
  12545. * @default true
  12546. */
  12547. this.isMaterial = true;
  12548. /**
  12549. * The ID of the material.
  12550. *
  12551. * @name Material#id
  12552. * @type {number}
  12553. * @readonly
  12554. */
  12555. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12556. /**
  12557. * The UUID of the material.
  12558. *
  12559. * @type {string}
  12560. * @readonly
  12561. */
  12562. this.uuid = generateUUID();
  12563. /**
  12564. * The name of the material.
  12565. *
  12566. * @type {string}
  12567. */
  12568. this.name = '';
  12569. /**
  12570. * The type property is used for detecting the object type
  12571. * in context of serialization/deserialization.
  12572. *
  12573. * @type {string}
  12574. * @readonly
  12575. */
  12576. this.type = 'Material';
  12577. /**
  12578. * Defines the blending type of the material.
  12579. *
  12580. * It must be set to `CustomBlending` if custom blending properties like
  12581. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12582. * should have any effect.
  12583. *
  12584. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12585. * @default NormalBlending
  12586. */
  12587. this.blending = NormalBlending;
  12588. /**
  12589. * Defines which side of faces will be rendered - front, back or both.
  12590. *
  12591. * @type {(FrontSide|BackSide|DoubleSide)}
  12592. * @default FrontSide
  12593. */
  12594. this.side = FrontSide;
  12595. /**
  12596. * If set to `true`, vertex colors should be used.
  12597. *
  12598. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12599. * four (RGBA) component color buffer attribute is used.
  12600. *
  12601. * @type {boolean}
  12602. * @default false
  12603. */
  12604. this.vertexColors = false;
  12605. /**
  12606. * Defines how transparent the material is.
  12607. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12608. *
  12609. * If the {@link Material#transparent} is not set to `true`,
  12610. * the material will remain fully opaque and this value will only affect its color.
  12611. *
  12612. * @type {number}
  12613. * @default 1
  12614. */
  12615. this.opacity = 1;
  12616. /**
  12617. * Defines whether this material is transparent. This has an effect on
  12618. * rendering as transparent objects need special treatment and are rendered
  12619. * after non-transparent objects.
  12620. *
  12621. * When set to true, the extent to which the material is transparent is
  12622. * controlled by {@link Material#opacity}.
  12623. *
  12624. * @type {boolean}
  12625. * @default false
  12626. */
  12627. this.transparent = false;
  12628. /**
  12629. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12630. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12631. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12632. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12633. *
  12634. * @type {boolean}
  12635. * @default false
  12636. */
  12637. this.alphaHash = false;
  12638. /**
  12639. * Defines the blending source factor.
  12640. *
  12641. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12642. * @default SrcAlphaFactor
  12643. */
  12644. this.blendSrc = SrcAlphaFactor;
  12645. /**
  12646. * Defines the blending destination factor.
  12647. *
  12648. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12649. * @default OneMinusSrcAlphaFactor
  12650. */
  12651. this.blendDst = OneMinusSrcAlphaFactor;
  12652. /**
  12653. * Defines the blending equation.
  12654. *
  12655. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12656. * @default AddEquation
  12657. */
  12658. this.blendEquation = AddEquation;
  12659. /**
  12660. * Defines the blending source alpha factor.
  12661. *
  12662. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12663. * @default null
  12664. */
  12665. this.blendSrcAlpha = null;
  12666. /**
  12667. * Defines the blending destination alpha factor.
  12668. *
  12669. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12670. * @default null
  12671. */
  12672. this.blendDstAlpha = null;
  12673. /**
  12674. * Defines the blending equation of the alpha channel.
  12675. *
  12676. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12677. * @default null
  12678. */
  12679. this.blendEquationAlpha = null;
  12680. /**
  12681. * Represents the RGB values of the constant blend color.
  12682. *
  12683. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12684. *
  12685. * @type {Color}
  12686. * @default (0,0,0)
  12687. */
  12688. this.blendColor = new Color( 0, 0, 0 );
  12689. /**
  12690. * Represents the alpha value of the constant blend color.
  12691. *
  12692. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12693. *
  12694. * @type {number}
  12695. * @default 0
  12696. */
  12697. this.blendAlpha = 0;
  12698. /**
  12699. * Defines the depth function.
  12700. *
  12701. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12702. * @default LessEqualDepth
  12703. */
  12704. this.depthFunc = LessEqualDepth;
  12705. /**
  12706. * Whether to have depth test enabled when rendering this material.
  12707. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12708. *
  12709. * @type {boolean}
  12710. * @default true
  12711. */
  12712. this.depthTest = true;
  12713. /**
  12714. * Whether rendering this material has any effect on the depth buffer.
  12715. *
  12716. * When drawing 2D overlays it can be useful to disable the depth writing in
  12717. * order to layer several things together without creating z-index artifacts.
  12718. *
  12719. * @type {boolean}
  12720. * @default true
  12721. */
  12722. this.depthWrite = true;
  12723. /**
  12724. * The bit mask to use when writing to the stencil buffer.
  12725. *
  12726. * @type {number}
  12727. * @default 0xff
  12728. */
  12729. this.stencilWriteMask = 0xff;
  12730. /**
  12731. * The stencil comparison function to use.
  12732. *
  12733. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12734. * @default AlwaysStencilFunc
  12735. */
  12736. this.stencilFunc = AlwaysStencilFunc;
  12737. /**
  12738. * The value to use when performing stencil comparisons or stencil operations.
  12739. *
  12740. * @type {number}
  12741. * @default 0
  12742. */
  12743. this.stencilRef = 0;
  12744. /**
  12745. * The bit mask to use when comparing against the stencil buffer.
  12746. *
  12747. * @type {number}
  12748. * @default 0xff
  12749. */
  12750. this.stencilFuncMask = 0xff;
  12751. /**
  12752. * Which stencil operation to perform when the comparison function returns `false`.
  12753. *
  12754. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12755. * @default KeepStencilOp
  12756. */
  12757. this.stencilFail = KeepStencilOp;
  12758. /**
  12759. * Which stencil operation to perform when the comparison function returns
  12760. * `true` but the depth test fails.
  12761. *
  12762. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12763. * @default KeepStencilOp
  12764. */
  12765. this.stencilZFail = KeepStencilOp;
  12766. /**
  12767. * Which stencil operation to perform when the comparison function returns
  12768. * `true` and the depth test passes.
  12769. *
  12770. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12771. * @default KeepStencilOp
  12772. */
  12773. this.stencilZPass = KeepStencilOp;
  12774. /**
  12775. * Whether stencil operations are performed against the stencil buffer. In
  12776. * order to perform writes or comparisons against the stencil buffer this
  12777. * value must be `true`.
  12778. *
  12779. * @type {boolean}
  12780. * @default false
  12781. */
  12782. this.stencilWrite = false;
  12783. /**
  12784. * User-defined clipping planes specified as THREE.Plane objects in world
  12785. * space. These planes apply to the objects this material is attached to.
  12786. * Points in space whose signed distance to the plane is negative are clipped
  12787. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12788. * be `true`.
  12789. *
  12790. * @type {?Array<Plane>}
  12791. * @default null
  12792. */
  12793. this.clippingPlanes = null;
  12794. /**
  12795. * Changes the behavior of clipping planes so that only their intersection is
  12796. * clipped, rather than their union.
  12797. *
  12798. * @type {boolean}
  12799. * @default false
  12800. */
  12801. this.clipIntersection = false;
  12802. /**
  12803. * Defines whether to clip shadows according to the clipping planes specified
  12804. * on this material.
  12805. *
  12806. * @type {boolean}
  12807. * @default false
  12808. */
  12809. this.clipShadows = false;
  12810. /**
  12811. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12812. * is determined as follows:
  12813. *
  12814. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12815. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12816. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12817. *
  12818. * @type {?(FrontSide|BackSide|DoubleSide)}
  12819. * @default null
  12820. */
  12821. this.shadowSide = null;
  12822. /**
  12823. * Whether to render the material's color.
  12824. *
  12825. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12826. * objects that occlude other objects.
  12827. *
  12828. * @type {boolean}
  12829. * @default true
  12830. */
  12831. this.colorWrite = true;
  12832. /**
  12833. * Override the renderer's default precision for this material.
  12834. *
  12835. * @type {?('highp'|'mediump'|'lowp')}
  12836. * @default null
  12837. */
  12838. this.precision = null;
  12839. /**
  12840. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12841. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12842. * The offset is added before the depth test is performed and before the value is written
  12843. * into the depth buffer.
  12844. *
  12845. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12846. * rendering solids with highlighted edges.
  12847. *
  12848. * @type {boolean}
  12849. * @default false
  12850. */
  12851. this.polygonOffset = false;
  12852. /**
  12853. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12854. *
  12855. * @type {number}
  12856. * @default 0
  12857. */
  12858. this.polygonOffsetFactor = 0;
  12859. /**
  12860. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12861. *
  12862. * @type {number}
  12863. * @default 0
  12864. */
  12865. this.polygonOffsetUnits = 0;
  12866. /**
  12867. * Whether to apply dithering to the color to remove the appearance of banding.
  12868. *
  12869. * @type {boolean}
  12870. * @default false
  12871. */
  12872. this.dithering = false;
  12873. /**
  12874. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12875. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12876. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12877. *
  12878. * @type {boolean}
  12879. * @default false
  12880. */
  12881. this.alphaToCoverage = false;
  12882. /**
  12883. * Whether to premultiply the alpha (transparency) value.
  12884. *
  12885. * @type {boolean}
  12886. * @default false
  12887. */
  12888. this.premultipliedAlpha = false;
  12889. /**
  12890. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12891. *
  12892. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12893. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12894. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12895. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12896. * disable the two pass rendering to avoid performance issues.
  12897. *
  12898. * @type {boolean}
  12899. * @default false
  12900. */
  12901. this.forceSinglePass = false;
  12902. /**
  12903. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12904. *
  12905. * @type {boolean}
  12906. * @default true
  12907. */
  12908. this.allowOverride = true;
  12909. /**
  12910. * Defines whether 3D objects using this material are visible.
  12911. *
  12912. * @type {boolean}
  12913. * @default true
  12914. */
  12915. this.visible = true;
  12916. /**
  12917. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12918. *
  12919. * It is ignored when rendering to a render target or using post processing or when using
  12920. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12921. *
  12922. * @type {boolean}
  12923. * @default true
  12924. */
  12925. this.toneMapped = true;
  12926. /**
  12927. * An object that can be used to store custom data about the Material. It
  12928. * should not hold references to functions as these will not be cloned.
  12929. *
  12930. * @type {Object}
  12931. */
  12932. this.userData = {};
  12933. /**
  12934. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12935. *
  12936. * @type {number}
  12937. * @readonly
  12938. * @default 0
  12939. */
  12940. this.version = 0;
  12941. this._alphaTest = 0;
  12942. }
  12943. /**
  12944. * Sets the alpha value to be used when running an alpha test. The material
  12945. * will not be rendered if the opacity is lower than this value.
  12946. *
  12947. * @type {number}
  12948. * @readonly
  12949. * @default 0
  12950. */
  12951. get alphaTest() {
  12952. return this._alphaTest;
  12953. }
  12954. set alphaTest( value ) {
  12955. if ( this._alphaTest > 0 !== value > 0 ) {
  12956. this.version ++;
  12957. }
  12958. this._alphaTest = value;
  12959. }
  12960. /**
  12961. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12962. *
  12963. * This method can only be used when rendering with {@link WebGLRenderer}.
  12964. *
  12965. * @param {WebGLRenderer} renderer - The renderer.
  12966. * @param {Scene} scene - The scene.
  12967. * @param {Camera} camera - The camera that is used to render the scene.
  12968. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12969. * @param {Object3D} object - The 3D object.
  12970. * @param {Object} group - The geometry group data.
  12971. */
  12972. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12973. /**
  12974. * An optional callback that is executed immediately before the shader
  12975. * program is compiled. This function is called with the shader source code
  12976. * as a parameter. Useful for the modification of built-in materials.
  12977. *
  12978. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12979. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12980. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12981. *
  12982. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12983. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12984. */
  12985. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12986. /**
  12987. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12988. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12989. * shader or recompile the shader for this material as needed.
  12990. *
  12991. * This method can only be used when rendering with {@link WebGLRenderer}.
  12992. *
  12993. * @return {string} The custom program cache key.
  12994. */
  12995. customProgramCacheKey() {
  12996. return this.onBeforeCompile.toString();
  12997. }
  12998. /**
  12999. * This method can be used to set default values from parameter objects.
  13000. * It is a generic implementation so it can be used with different types
  13001. * of materials.
  13002. *
  13003. * @param {Object} [values] - The material values to set.
  13004. */
  13005. setValues( values ) {
  13006. if ( values === undefined ) return;
  13007. for ( const key in values ) {
  13008. const newValue = values[ key ];
  13009. if ( newValue === undefined ) {
  13010. warn( `Material: parameter '${ key }' has value of undefined.` );
  13011. continue;
  13012. }
  13013. const currentValue = this[ key ];
  13014. if ( currentValue === undefined ) {
  13015. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  13016. continue;
  13017. }
  13018. if ( currentValue && currentValue.isColor ) {
  13019. currentValue.set( newValue );
  13020. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  13021. currentValue.copy( newValue );
  13022. } else {
  13023. this[ key ] = newValue;
  13024. }
  13025. }
  13026. }
  13027. /**
  13028. * Serializes the material into JSON.
  13029. *
  13030. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13031. * @return {Object} A JSON object representing the serialized material.
  13032. * @see {@link ObjectLoader#parse}
  13033. */
  13034. toJSON( meta ) {
  13035. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  13036. if ( isRootObject ) {
  13037. meta = {
  13038. textures: {},
  13039. images: {}
  13040. };
  13041. }
  13042. const data = {
  13043. metadata: {
  13044. version: 4.7,
  13045. type: 'Material',
  13046. generator: 'Material.toJSON'
  13047. }
  13048. };
  13049. // standard Material serialization
  13050. data.uuid = this.uuid;
  13051. data.type = this.type;
  13052. if ( this.name !== '' ) data.name = this.name;
  13053. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  13054. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  13055. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  13056. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  13057. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  13058. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  13059. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  13060. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  13061. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  13062. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  13063. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  13064. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  13065. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  13066. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  13067. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  13068. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  13069. }
  13070. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  13071. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  13072. }
  13073. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  13074. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  13075. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  13076. }
  13077. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  13078. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  13079. }
  13080. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  13081. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  13082. }
  13083. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  13084. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  13085. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  13086. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  13087. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  13088. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  13089. }
  13090. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  13091. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  13092. }
  13093. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  13094. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  13095. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  13096. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  13097. }
  13098. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  13099. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  13100. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  13101. if ( this.lightMap && this.lightMap.isTexture ) {
  13102. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  13103. data.lightMapIntensity = this.lightMapIntensity;
  13104. }
  13105. if ( this.aoMap && this.aoMap.isTexture ) {
  13106. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  13107. data.aoMapIntensity = this.aoMapIntensity;
  13108. }
  13109. if ( this.bumpMap && this.bumpMap.isTexture ) {
  13110. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  13111. data.bumpScale = this.bumpScale;
  13112. }
  13113. if ( this.normalMap && this.normalMap.isTexture ) {
  13114. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  13115. data.normalMapType = this.normalMapType;
  13116. data.normalScale = this.normalScale.toArray();
  13117. }
  13118. if ( this.displacementMap && this.displacementMap.isTexture ) {
  13119. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  13120. data.displacementScale = this.displacementScale;
  13121. data.displacementBias = this.displacementBias;
  13122. }
  13123. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  13124. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  13125. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  13126. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  13127. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  13128. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  13129. if ( this.envMap && this.envMap.isTexture ) {
  13130. data.envMap = this.envMap.toJSON( meta ).uuid;
  13131. if ( this.combine !== undefined ) data.combine = this.combine;
  13132. }
  13133. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  13134. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  13135. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  13136. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  13137. if ( this.gradientMap && this.gradientMap.isTexture ) {
  13138. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  13139. }
  13140. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  13141. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  13142. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  13143. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  13144. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  13145. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  13146. if ( this.size !== undefined ) data.size = this.size;
  13147. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  13148. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  13149. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  13150. if ( this.side !== FrontSide ) data.side = this.side;
  13151. if ( this.vertexColors === true ) data.vertexColors = true;
  13152. if ( this.opacity < 1 ) data.opacity = this.opacity;
  13153. if ( this.transparent === true ) data.transparent = true;
  13154. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  13155. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  13156. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  13157. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  13158. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  13159. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  13160. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  13161. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  13162. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  13163. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  13164. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  13165. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  13166. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  13167. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  13168. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  13169. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  13170. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  13171. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  13172. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  13173. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  13174. // rotation (SpriteMaterial)
  13175. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  13176. if ( this.polygonOffset === true ) data.polygonOffset = true;
  13177. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  13178. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  13179. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  13180. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  13181. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  13182. if ( this.scale !== undefined ) data.scale = this.scale;
  13183. if ( this.dithering === true ) data.dithering = true;
  13184. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  13185. if ( this.alphaHash === true ) data.alphaHash = true;
  13186. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  13187. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  13188. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  13189. if ( this.allowOverride === false ) data.allowOverride = false;
  13190. if ( this.wireframe === true ) data.wireframe = true;
  13191. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  13192. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  13193. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13194. if ( this.flatShading === true ) data.flatShading = true;
  13195. if ( this.visible === false ) data.visible = false;
  13196. if ( this.toneMapped === false ) data.toneMapped = false;
  13197. if ( this.fog === false ) data.fog = false;
  13198. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13199. // TODO: Copied from Object3D.toJSON
  13200. function extractFromCache( cache ) {
  13201. const values = [];
  13202. for ( const key in cache ) {
  13203. const data = cache[ key ];
  13204. delete data.metadata;
  13205. values.push( data );
  13206. }
  13207. return values;
  13208. }
  13209. if ( isRootObject ) {
  13210. const textures = extractFromCache( meta.textures );
  13211. const images = extractFromCache( meta.images );
  13212. if ( textures.length > 0 ) data.textures = textures;
  13213. if ( images.length > 0 ) data.images = images;
  13214. }
  13215. return data;
  13216. }
  13217. /**
  13218. * Returns a new material with copied values from this instance.
  13219. *
  13220. * @return {Material} A clone of this instance.
  13221. */
  13222. clone() {
  13223. return new this.constructor().copy( this );
  13224. }
  13225. /**
  13226. * Copies the values of the given material to this instance.
  13227. *
  13228. * @param {Material} source - The material to copy.
  13229. * @return {Material} A reference to this instance.
  13230. */
  13231. copy( source ) {
  13232. this.name = source.name;
  13233. this.blending = source.blending;
  13234. this.side = source.side;
  13235. this.vertexColors = source.vertexColors;
  13236. this.opacity = source.opacity;
  13237. this.transparent = source.transparent;
  13238. this.blendSrc = source.blendSrc;
  13239. this.blendDst = source.blendDst;
  13240. this.blendEquation = source.blendEquation;
  13241. this.blendSrcAlpha = source.blendSrcAlpha;
  13242. this.blendDstAlpha = source.blendDstAlpha;
  13243. this.blendEquationAlpha = source.blendEquationAlpha;
  13244. this.blendColor.copy( source.blendColor );
  13245. this.blendAlpha = source.blendAlpha;
  13246. this.depthFunc = source.depthFunc;
  13247. this.depthTest = source.depthTest;
  13248. this.depthWrite = source.depthWrite;
  13249. this.stencilWriteMask = source.stencilWriteMask;
  13250. this.stencilFunc = source.stencilFunc;
  13251. this.stencilRef = source.stencilRef;
  13252. this.stencilFuncMask = source.stencilFuncMask;
  13253. this.stencilFail = source.stencilFail;
  13254. this.stencilZFail = source.stencilZFail;
  13255. this.stencilZPass = source.stencilZPass;
  13256. this.stencilWrite = source.stencilWrite;
  13257. const srcPlanes = source.clippingPlanes;
  13258. let dstPlanes = null;
  13259. if ( srcPlanes !== null ) {
  13260. const n = srcPlanes.length;
  13261. dstPlanes = new Array( n );
  13262. for ( let i = 0; i !== n; ++ i ) {
  13263. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13264. }
  13265. }
  13266. this.clippingPlanes = dstPlanes;
  13267. this.clipIntersection = source.clipIntersection;
  13268. this.clipShadows = source.clipShadows;
  13269. this.shadowSide = source.shadowSide;
  13270. this.colorWrite = source.colorWrite;
  13271. this.precision = source.precision;
  13272. this.polygonOffset = source.polygonOffset;
  13273. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13274. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13275. this.dithering = source.dithering;
  13276. this.alphaTest = source.alphaTest;
  13277. this.alphaHash = source.alphaHash;
  13278. this.alphaToCoverage = source.alphaToCoverage;
  13279. this.premultipliedAlpha = source.premultipliedAlpha;
  13280. this.forceSinglePass = source.forceSinglePass;
  13281. this.allowOverride = source.allowOverride;
  13282. this.visible = source.visible;
  13283. this.toneMapped = source.toneMapped;
  13284. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13285. return this;
  13286. }
  13287. /**
  13288. * Frees the GPU-related resources allocated by this instance. Call this
  13289. * method whenever this instance is no longer used in your app.
  13290. *
  13291. * @fires Material#dispose
  13292. */
  13293. dispose() {
  13294. /**
  13295. * Fires when the material has been disposed of.
  13296. *
  13297. * @event Material#dispose
  13298. * @type {Object}
  13299. */
  13300. this.dispatchEvent( { type: 'dispose' } );
  13301. }
  13302. /**
  13303. * Setting this property to `true` indicates the engine the material
  13304. * needs to be recompiled.
  13305. *
  13306. * @type {boolean}
  13307. * @default false
  13308. * @param {boolean} value
  13309. */
  13310. set needsUpdate( value ) {
  13311. if ( value === true ) this.version ++;
  13312. }
  13313. }
  13314. /**
  13315. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13316. *
  13317. * This material is not affected by lights.
  13318. *
  13319. * @augments Material
  13320. * @demo scenes/material-browser.html#MeshBasicMaterial
  13321. */
  13322. class MeshBasicMaterial extends Material {
  13323. /**
  13324. * Constructs a new mesh basic material.
  13325. *
  13326. * @param {Object} [parameters] - An object with one or more properties
  13327. * defining the material's appearance. Any property of the material
  13328. * (including any property from inherited materials) can be passed
  13329. * in here. Color values can be passed any type of value accepted
  13330. * by {@link Color#set}.
  13331. */
  13332. constructor( parameters ) {
  13333. super();
  13334. /**
  13335. * This flag can be used for type testing.
  13336. *
  13337. * @type {boolean}
  13338. * @readonly
  13339. * @default true
  13340. */
  13341. this.isMeshBasicMaterial = true;
  13342. this.type = 'MeshBasicMaterial';
  13343. /**
  13344. * Color of the material.
  13345. *
  13346. * @type {Color}
  13347. * @default (1,1,1)
  13348. */
  13349. this.color = new Color( 0xffffff ); // diffuse
  13350. /**
  13351. * The color map. May optionally include an alpha channel, typically combined
  13352. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13353. * color is modulated by the diffuse `color`.
  13354. *
  13355. * @type {?Texture}
  13356. * @default null
  13357. */
  13358. this.map = null;
  13359. /**
  13360. * The light map. Requires a second set of UVs.
  13361. *
  13362. * @type {?Texture}
  13363. * @default null
  13364. */
  13365. this.lightMap = null;
  13366. /**
  13367. * Intensity of the baked light.
  13368. *
  13369. * @type {number}
  13370. * @default 1
  13371. */
  13372. this.lightMapIntensity = 1.0;
  13373. /**
  13374. * The red channel of this texture is used as the ambient occlusion map.
  13375. * Requires a second set of UVs.
  13376. *
  13377. * @type {?Texture}
  13378. * @default null
  13379. */
  13380. this.aoMap = null;
  13381. /**
  13382. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13383. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13384. * red channel is also `1`, ambient light is fully occluded on a surface.
  13385. *
  13386. * @type {number}
  13387. * @default 1
  13388. */
  13389. this.aoMapIntensity = 1.0;
  13390. /**
  13391. * Specular map used by the material.
  13392. *
  13393. * @type {?Texture}
  13394. * @default null
  13395. */
  13396. this.specularMap = null;
  13397. /**
  13398. * The alpha map is a grayscale texture that controls the opacity across the
  13399. * surface (black: fully transparent; white: fully opaque).
  13400. *
  13401. * Only the color of the texture is used, ignoring the alpha channel if one
  13402. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13403. * when sampling this texture due to the extra bit of precision provided for
  13404. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13405. * luminance/alpha textures will also still work as expected.
  13406. *
  13407. * @type {?Texture}
  13408. * @default null
  13409. */
  13410. this.alphaMap = null;
  13411. /**
  13412. * The environment map.
  13413. *
  13414. * @type {?Texture}
  13415. * @default null
  13416. */
  13417. this.envMap = null;
  13418. /**
  13419. * The rotation of the environment map in radians.
  13420. *
  13421. * @type {Euler}
  13422. * @default (0,0,0)
  13423. */
  13424. this.envMapRotation = new Euler();
  13425. /**
  13426. * How to combine the result of the surface's color with the environment map, if any.
  13427. *
  13428. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13429. * blend between the two colors.
  13430. *
  13431. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13432. * @default MultiplyOperation
  13433. */
  13434. this.combine = MultiplyOperation;
  13435. /**
  13436. * How much the environment map affects the surface.
  13437. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13438. *
  13439. * @type {number}
  13440. * @default 1
  13441. */
  13442. this.reflectivity = 1;
  13443. /**
  13444. * The index of refraction (IOR) of air (approximately 1) divided by the
  13445. * index of refraction of the material. It is used with environment mapping
  13446. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13447. * The refraction ratio should not exceed `1`.
  13448. *
  13449. * @type {number}
  13450. * @default 0.98
  13451. */
  13452. this.refractionRatio = 0.98;
  13453. /**
  13454. * Renders the geometry as a wireframe.
  13455. *
  13456. * @type {boolean}
  13457. * @default false
  13458. */
  13459. this.wireframe = false;
  13460. /**
  13461. * Controls the thickness of the wireframe.
  13462. *
  13463. * Can only be used with {@link SVGRenderer}.
  13464. *
  13465. * @type {number}
  13466. * @default 1
  13467. */
  13468. this.wireframeLinewidth = 1;
  13469. /**
  13470. * Defines appearance of wireframe ends.
  13471. *
  13472. * Can only be used with {@link SVGRenderer}.
  13473. *
  13474. * @type {('round'|'bevel'|'miter')}
  13475. * @default 'round'
  13476. */
  13477. this.wireframeLinecap = 'round';
  13478. /**
  13479. * Defines appearance of wireframe joints.
  13480. *
  13481. * Can only be used with {@link SVGRenderer}.
  13482. *
  13483. * @type {('round'|'bevel'|'miter')}
  13484. * @default 'round'
  13485. */
  13486. this.wireframeLinejoin = 'round';
  13487. /**
  13488. * Whether the material is affected by fog or not.
  13489. *
  13490. * @type {boolean}
  13491. * @default true
  13492. */
  13493. this.fog = true;
  13494. this.setValues( parameters );
  13495. }
  13496. copy( source ) {
  13497. super.copy( source );
  13498. this.color.copy( source.color );
  13499. this.map = source.map;
  13500. this.lightMap = source.lightMap;
  13501. this.lightMapIntensity = source.lightMapIntensity;
  13502. this.aoMap = source.aoMap;
  13503. this.aoMapIntensity = source.aoMapIntensity;
  13504. this.specularMap = source.specularMap;
  13505. this.alphaMap = source.alphaMap;
  13506. this.envMap = source.envMap;
  13507. this.envMapRotation.copy( source.envMapRotation );
  13508. this.combine = source.combine;
  13509. this.reflectivity = source.reflectivity;
  13510. this.refractionRatio = source.refractionRatio;
  13511. this.wireframe = source.wireframe;
  13512. this.wireframeLinewidth = source.wireframeLinewidth;
  13513. this.wireframeLinecap = source.wireframeLinecap;
  13514. this.wireframeLinejoin = source.wireframeLinejoin;
  13515. this.fog = source.fog;
  13516. return this;
  13517. }
  13518. }
  13519. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13520. const _tables = /*@__PURE__*/ _generateTables();
  13521. function _generateTables() {
  13522. // float32 to float16 helpers
  13523. const buffer = new ArrayBuffer( 4 );
  13524. const floatView = new Float32Array( buffer );
  13525. const uint32View = new Uint32Array( buffer );
  13526. const baseTable = new Uint32Array( 512 );
  13527. const shiftTable = new Uint32Array( 512 );
  13528. for ( let i = 0; i < 256; ++ i ) {
  13529. const e = i - 127;
  13530. // very small number (0, -0)
  13531. if ( e < -27 ) {
  13532. baseTable[ i ] = 0x0000;
  13533. baseTable[ i | 0x100 ] = 0x8000;
  13534. shiftTable[ i ] = 24;
  13535. shiftTable[ i | 0x100 ] = 24;
  13536. // small number (denorm)
  13537. } else if ( e < -14 ) {
  13538. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13539. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13540. shiftTable[ i ] = - e - 1;
  13541. shiftTable[ i | 0x100 ] = - e - 1;
  13542. // normal number
  13543. } else if ( e <= 15 ) {
  13544. baseTable[ i ] = ( e + 15 ) << 10;
  13545. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13546. shiftTable[ i ] = 13;
  13547. shiftTable[ i | 0x100 ] = 13;
  13548. // large number (Infinity, -Infinity)
  13549. } else if ( e < 128 ) {
  13550. baseTable[ i ] = 0x7c00;
  13551. baseTable[ i | 0x100 ] = 0xfc00;
  13552. shiftTable[ i ] = 24;
  13553. shiftTable[ i | 0x100 ] = 24;
  13554. // stay (NaN, Infinity, -Infinity)
  13555. } else {
  13556. baseTable[ i ] = 0x7c00;
  13557. baseTable[ i | 0x100 ] = 0xfc00;
  13558. shiftTable[ i ] = 13;
  13559. shiftTable[ i | 0x100 ] = 13;
  13560. }
  13561. }
  13562. // float16 to float32 helpers
  13563. const mantissaTable = new Uint32Array( 2048 );
  13564. const exponentTable = new Uint32Array( 64 );
  13565. const offsetTable = new Uint32Array( 64 );
  13566. for ( let i = 1; i < 1024; ++ i ) {
  13567. let m = i << 13; // zero pad mantissa bits
  13568. let e = 0; // zero exponent
  13569. // normalized
  13570. while ( ( m & 0x00800000 ) === 0 ) {
  13571. m <<= 1;
  13572. e -= 0x00800000; // decrement exponent
  13573. }
  13574. m &= -8388609; // clear leading 1 bit
  13575. e += 0x38800000; // adjust bias
  13576. mantissaTable[ i ] = m | e;
  13577. }
  13578. for ( let i = 1024; i < 2048; ++ i ) {
  13579. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13580. }
  13581. for ( let i = 1; i < 31; ++ i ) {
  13582. exponentTable[ i ] = i << 23;
  13583. }
  13584. exponentTable[ 31 ] = 0x47800000;
  13585. exponentTable[ 32 ] = 0x80000000;
  13586. for ( let i = 33; i < 63; ++ i ) {
  13587. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13588. }
  13589. exponentTable[ 63 ] = 0xc7800000;
  13590. for ( let i = 1; i < 64; ++ i ) {
  13591. if ( i !== 32 ) {
  13592. offsetTable[ i ] = 1024;
  13593. }
  13594. }
  13595. return {
  13596. floatView: floatView,
  13597. uint32View: uint32View,
  13598. baseTable: baseTable,
  13599. shiftTable: shiftTable,
  13600. mantissaTable: mantissaTable,
  13601. exponentTable: exponentTable,
  13602. offsetTable: offsetTable
  13603. };
  13604. }
  13605. /**
  13606. * Returns a half precision floating point value (FP16) from the given single
  13607. * precision floating point value (FP32).
  13608. *
  13609. * @param {number} val - A single precision floating point value.
  13610. * @return {number} The FP16 value.
  13611. */
  13612. function toHalfFloat( val ) {
  13613. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13614. val = clamp( val, -65504, 65504 );
  13615. _tables.floatView[ 0 ] = val;
  13616. const f = _tables.uint32View[ 0 ];
  13617. const e = ( f >> 23 ) & 0x1ff;
  13618. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13619. }
  13620. /**
  13621. * Returns a single precision floating point value (FP32) from the given half
  13622. * precision floating point value (FP16).
  13623. *
  13624. * @param {number} val - A half precision floating point value.
  13625. * @return {number} The FP32 value.
  13626. */
  13627. function fromHalfFloat( val ) {
  13628. const m = val >> 10;
  13629. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13630. return _tables.floatView[ 0 ];
  13631. }
  13632. /**
  13633. * A class containing utility functions for data.
  13634. *
  13635. * @hideconstructor
  13636. */
  13637. class DataUtils {
  13638. /**
  13639. * Returns a half precision floating point value (FP16) from the given single
  13640. * precision floating point value (FP32).
  13641. *
  13642. * @param {number} val - A single precision floating point value.
  13643. * @return {number} The FP16 value.
  13644. */
  13645. static toHalfFloat( val ) {
  13646. return toHalfFloat( val );
  13647. }
  13648. /**
  13649. * Returns a single precision floating point value (FP32) from the given half
  13650. * precision floating point value (FP16).
  13651. *
  13652. * @param {number} val - A half precision floating point value.
  13653. * @return {number} The FP32 value.
  13654. */
  13655. static fromHalfFloat( val ) {
  13656. return fromHalfFloat( val );
  13657. }
  13658. }
  13659. const _vector$9 = /*@__PURE__*/ new Vector3();
  13660. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13661. let _id$3 = 0;
  13662. /**
  13663. * This class stores data for an attribute (such as vertex positions, face
  13664. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13665. * a geometry, which allows for more efficient passing of data to the GPU.
  13666. *
  13667. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13668. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13669. */
  13670. class BufferAttribute {
  13671. /**
  13672. * Constructs a new buffer attribute.
  13673. *
  13674. * @param {TypedArray} array - The array holding the attribute data.
  13675. * @param {number} itemSize - The item size.
  13676. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13677. */
  13678. constructor( array, itemSize, normalized = false ) {
  13679. if ( Array.isArray( array ) ) {
  13680. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13681. }
  13682. /**
  13683. * This flag can be used for type testing.
  13684. *
  13685. * @type {boolean}
  13686. * @readonly
  13687. * @default true
  13688. */
  13689. this.isBufferAttribute = true;
  13690. /**
  13691. * The ID of the buffer attribute.
  13692. *
  13693. * @name BufferAttribute#id
  13694. * @type {number}
  13695. * @readonly
  13696. */
  13697. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13698. /**
  13699. * The name of the buffer attribute.
  13700. *
  13701. * @type {string}
  13702. */
  13703. this.name = '';
  13704. /**
  13705. * The array holding the attribute data. It should have `itemSize * numVertices`
  13706. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13707. *
  13708. * @type {TypedArray}
  13709. */
  13710. this.array = array;
  13711. /**
  13712. * The number of values of the array that should be associated with a particular vertex.
  13713. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13714. * normal, or color), then the value should be `3`.
  13715. *
  13716. * @type {number}
  13717. */
  13718. this.itemSize = itemSize;
  13719. /**
  13720. * Represents the number of items this buffer attribute stores. It is internally computed
  13721. * by dividing the `array` length by the `itemSize`.
  13722. *
  13723. * @type {number}
  13724. * @readonly
  13725. */
  13726. this.count = array !== undefined ? array.length / itemSize : 0;
  13727. /**
  13728. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13729. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13730. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13731. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13732. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13733. *
  13734. * @type {boolean}
  13735. */
  13736. this.normalized = normalized;
  13737. /**
  13738. * Defines the intended usage pattern of the data store for optimization purposes.
  13739. *
  13740. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13741. * instantiate a new one and set the desired usage before the next render.
  13742. *
  13743. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13744. * @default StaticDrawUsage
  13745. */
  13746. this.usage = StaticDrawUsage;
  13747. /**
  13748. * This can be used to only update some components of stored vectors (for example, just the
  13749. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13750. *
  13751. * @type {Array<Object>}
  13752. */
  13753. this.updateRanges = [];
  13754. /**
  13755. * Configures the bound GPU type for use in shaders.
  13756. *
  13757. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13758. * For lower precision float types, use `Float16BufferAttribute`.
  13759. *
  13760. * @type {(FloatType|IntType)}
  13761. * @default FloatType
  13762. */
  13763. this.gpuType = FloatType;
  13764. /**
  13765. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13766. *
  13767. * @type {number}
  13768. */
  13769. this.version = 0;
  13770. }
  13771. /**
  13772. * A callback function that is executed after the renderer has transferred the attribute
  13773. * array data to the GPU.
  13774. */
  13775. onUploadCallback() {}
  13776. /**
  13777. * Flag to indicate that this attribute has changed and should be re-sent to
  13778. * the GPU. Set this to `true` when you modify the value of the array.
  13779. *
  13780. * @type {number}
  13781. * @default false
  13782. * @param {boolean} value
  13783. */
  13784. set needsUpdate( value ) {
  13785. if ( value === true ) this.version ++;
  13786. }
  13787. /**
  13788. * Sets the usage of this buffer attribute.
  13789. *
  13790. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13791. * @return {BufferAttribute} A reference to this buffer attribute.
  13792. */
  13793. setUsage( value ) {
  13794. this.usage = value;
  13795. return this;
  13796. }
  13797. /**
  13798. * Adds a range of data in the data array to be updated on the GPU.
  13799. *
  13800. * @param {number} start - Position at which to start update.
  13801. * @param {number} count - The number of components to update.
  13802. */
  13803. addUpdateRange( start, count ) {
  13804. this.updateRanges.push( { start, count } );
  13805. }
  13806. /**
  13807. * Clears the update ranges.
  13808. */
  13809. clearUpdateRanges() {
  13810. this.updateRanges.length = 0;
  13811. }
  13812. /**
  13813. * Copies the values of the given buffer attribute to this instance.
  13814. *
  13815. * @param {BufferAttribute} source - The buffer attribute to copy.
  13816. * @return {BufferAttribute} A reference to this instance.
  13817. */
  13818. copy( source ) {
  13819. this.name = source.name;
  13820. this.array = new source.array.constructor( source.array );
  13821. this.itemSize = source.itemSize;
  13822. this.count = source.count;
  13823. this.normalized = source.normalized;
  13824. this.usage = source.usage;
  13825. this.gpuType = source.gpuType;
  13826. return this;
  13827. }
  13828. /**
  13829. * Copies a vector from the given buffer attribute to this one. The start
  13830. * and destination position in the attribute buffers are represented by the
  13831. * given indices.
  13832. *
  13833. * @param {number} index1 - The destination index into this buffer attribute.
  13834. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13835. * @param {number} index2 - The source index into the given buffer attribute.
  13836. * @return {BufferAttribute} A reference to this instance.
  13837. */
  13838. copyAt( index1, attribute, index2 ) {
  13839. index1 *= this.itemSize;
  13840. index2 *= attribute.itemSize;
  13841. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13842. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13843. }
  13844. return this;
  13845. }
  13846. /**
  13847. * Copies the given array data into this buffer attribute.
  13848. *
  13849. * @param {(TypedArray|Array)} array - The array to copy.
  13850. * @return {BufferAttribute} A reference to this instance.
  13851. */
  13852. copyArray( array ) {
  13853. this.array.set( array );
  13854. return this;
  13855. }
  13856. /**
  13857. * Applies the given 3x3 matrix to the given attribute. Works with
  13858. * item size `2` and `3`.
  13859. *
  13860. * @param {Matrix3} m - The matrix to apply.
  13861. * @return {BufferAttribute} A reference to this instance.
  13862. */
  13863. applyMatrix3( m ) {
  13864. if ( this.itemSize === 2 ) {
  13865. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13866. _vector2$1.fromBufferAttribute( this, i );
  13867. _vector2$1.applyMatrix3( m );
  13868. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13869. }
  13870. } else if ( this.itemSize === 3 ) {
  13871. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13872. _vector$9.fromBufferAttribute( this, i );
  13873. _vector$9.applyMatrix3( m );
  13874. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13875. }
  13876. }
  13877. return this;
  13878. }
  13879. /**
  13880. * Applies the given 4x4 matrix to the given attribute. Only works with
  13881. * item size `3`.
  13882. *
  13883. * @param {Matrix4} m - The matrix to apply.
  13884. * @return {BufferAttribute} A reference to this instance.
  13885. */
  13886. applyMatrix4( m ) {
  13887. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13888. _vector$9.fromBufferAttribute( this, i );
  13889. _vector$9.applyMatrix4( m );
  13890. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13891. }
  13892. return this;
  13893. }
  13894. /**
  13895. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13896. * item size `3`.
  13897. *
  13898. * @param {Matrix3} m - The normal matrix to apply.
  13899. * @return {BufferAttribute} A reference to this instance.
  13900. */
  13901. applyNormalMatrix( m ) {
  13902. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13903. _vector$9.fromBufferAttribute( this, i );
  13904. _vector$9.applyNormalMatrix( m );
  13905. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13906. }
  13907. return this;
  13908. }
  13909. /**
  13910. * Applies the given 4x4 matrix to the given attribute. Only works with
  13911. * item size `3` and with direction vectors.
  13912. *
  13913. * @param {Matrix4} m - The matrix to apply.
  13914. * @return {BufferAttribute} A reference to this instance.
  13915. */
  13916. transformDirection( m ) {
  13917. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13918. _vector$9.fromBufferAttribute( this, i );
  13919. _vector$9.transformDirection( m );
  13920. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13921. }
  13922. return this;
  13923. }
  13924. /**
  13925. * Sets the given array data in the buffer attribute.
  13926. *
  13927. * @param {(TypedArray|Array)} value - The array data to set.
  13928. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13929. * @return {BufferAttribute} A reference to this instance.
  13930. */
  13931. set( value, offset = 0 ) {
  13932. // Matching BufferAttribute constructor, do not normalize the array.
  13933. this.array.set( value, offset );
  13934. return this;
  13935. }
  13936. /**
  13937. * Returns the given component of the vector at the given index.
  13938. *
  13939. * @param {number} index - The index into the buffer attribute.
  13940. * @param {number} component - The component index.
  13941. * @return {number} The returned value.
  13942. */
  13943. getComponent( index, component ) {
  13944. let value = this.array[ index * this.itemSize + component ];
  13945. if ( this.normalized ) value = denormalize( value, this.array );
  13946. return value;
  13947. }
  13948. /**
  13949. * Sets the given value to the given component of the vector at the given index.
  13950. *
  13951. * @param {number} index - The index into the buffer attribute.
  13952. * @param {number} component - The component index.
  13953. * @param {number} value - The value to set.
  13954. * @return {BufferAttribute} A reference to this instance.
  13955. */
  13956. setComponent( index, component, value ) {
  13957. if ( this.normalized ) value = normalize( value, this.array );
  13958. this.array[ index * this.itemSize + component ] = value;
  13959. return this;
  13960. }
  13961. /**
  13962. * Returns the x component of the vector at the given index.
  13963. *
  13964. * @param {number} index - The index into the buffer attribute.
  13965. * @return {number} The x component.
  13966. */
  13967. getX( index ) {
  13968. let x = this.array[ index * this.itemSize ];
  13969. if ( this.normalized ) x = denormalize( x, this.array );
  13970. return x;
  13971. }
  13972. /**
  13973. * Sets the x component of the vector at the given index.
  13974. *
  13975. * @param {number} index - The index into the buffer attribute.
  13976. * @param {number} x - The value to set.
  13977. * @return {BufferAttribute} A reference to this instance.
  13978. */
  13979. setX( index, x ) {
  13980. if ( this.normalized ) x = normalize( x, this.array );
  13981. this.array[ index * this.itemSize ] = x;
  13982. return this;
  13983. }
  13984. /**
  13985. * Returns the y component of the vector at the given index.
  13986. *
  13987. * @param {number} index - The index into the buffer attribute.
  13988. * @return {number} The y component.
  13989. */
  13990. getY( index ) {
  13991. let y = this.array[ index * this.itemSize + 1 ];
  13992. if ( this.normalized ) y = denormalize( y, this.array );
  13993. return y;
  13994. }
  13995. /**
  13996. * Sets the y component of the vector at the given index.
  13997. *
  13998. * @param {number} index - The index into the buffer attribute.
  13999. * @param {number} y - The value to set.
  14000. * @return {BufferAttribute} A reference to this instance.
  14001. */
  14002. setY( index, y ) {
  14003. if ( this.normalized ) y = normalize( y, this.array );
  14004. this.array[ index * this.itemSize + 1 ] = y;
  14005. return this;
  14006. }
  14007. /**
  14008. * Returns the z component of the vector at the given index.
  14009. *
  14010. * @param {number} index - The index into the buffer attribute.
  14011. * @return {number} The z component.
  14012. */
  14013. getZ( index ) {
  14014. let z = this.array[ index * this.itemSize + 2 ];
  14015. if ( this.normalized ) z = denormalize( z, this.array );
  14016. return z;
  14017. }
  14018. /**
  14019. * Sets the z component of the vector at the given index.
  14020. *
  14021. * @param {number} index - The index into the buffer attribute.
  14022. * @param {number} z - The value to set.
  14023. * @return {BufferAttribute} A reference to this instance.
  14024. */
  14025. setZ( index, z ) {
  14026. if ( this.normalized ) z = normalize( z, this.array );
  14027. this.array[ index * this.itemSize + 2 ] = z;
  14028. return this;
  14029. }
  14030. /**
  14031. * Returns the w component of the vector at the given index.
  14032. *
  14033. * @param {number} index - The index into the buffer attribute.
  14034. * @return {number} The w component.
  14035. */
  14036. getW( index ) {
  14037. let w = this.array[ index * this.itemSize + 3 ];
  14038. if ( this.normalized ) w = denormalize( w, this.array );
  14039. return w;
  14040. }
  14041. /**
  14042. * Sets the w component of the vector at the given index.
  14043. *
  14044. * @param {number} index - The index into the buffer attribute.
  14045. * @param {number} w - The value to set.
  14046. * @return {BufferAttribute} A reference to this instance.
  14047. */
  14048. setW( index, w ) {
  14049. if ( this.normalized ) w = normalize( w, this.array );
  14050. this.array[ index * this.itemSize + 3 ] = w;
  14051. return this;
  14052. }
  14053. /**
  14054. * Sets the x and y component of the vector at the given index.
  14055. *
  14056. * @param {number} index - The index into the buffer attribute.
  14057. * @param {number} x - The value for the x component to set.
  14058. * @param {number} y - The value for the y component to set.
  14059. * @return {BufferAttribute} A reference to this instance.
  14060. */
  14061. setXY( index, x, y ) {
  14062. index *= this.itemSize;
  14063. if ( this.normalized ) {
  14064. x = normalize( x, this.array );
  14065. y = normalize( y, this.array );
  14066. }
  14067. this.array[ index + 0 ] = x;
  14068. this.array[ index + 1 ] = y;
  14069. return this;
  14070. }
  14071. /**
  14072. * Sets the x, y and z component of the vector at the given index.
  14073. *
  14074. * @param {number} index - The index into the buffer attribute.
  14075. * @param {number} x - The value for the x component to set.
  14076. * @param {number} y - The value for the y component to set.
  14077. * @param {number} z - The value for the z component to set.
  14078. * @return {BufferAttribute} A reference to this instance.
  14079. */
  14080. setXYZ( index, x, y, z ) {
  14081. index *= this.itemSize;
  14082. if ( this.normalized ) {
  14083. x = normalize( x, this.array );
  14084. y = normalize( y, this.array );
  14085. z = normalize( z, this.array );
  14086. }
  14087. this.array[ index + 0 ] = x;
  14088. this.array[ index + 1 ] = y;
  14089. this.array[ index + 2 ] = z;
  14090. return this;
  14091. }
  14092. /**
  14093. * Sets the x, y, z and w component of the vector at the given index.
  14094. *
  14095. * @param {number} index - The index into the buffer attribute.
  14096. * @param {number} x - The value for the x component to set.
  14097. * @param {number} y - The value for the y component to set.
  14098. * @param {number} z - The value for the z component to set.
  14099. * @param {number} w - The value for the w component to set.
  14100. * @return {BufferAttribute} A reference to this instance.
  14101. */
  14102. setXYZW( index, x, y, z, w ) {
  14103. index *= this.itemSize;
  14104. if ( this.normalized ) {
  14105. x = normalize( x, this.array );
  14106. y = normalize( y, this.array );
  14107. z = normalize( z, this.array );
  14108. w = normalize( w, this.array );
  14109. }
  14110. this.array[ index + 0 ] = x;
  14111. this.array[ index + 1 ] = y;
  14112. this.array[ index + 2 ] = z;
  14113. this.array[ index + 3 ] = w;
  14114. return this;
  14115. }
  14116. /**
  14117. * Sets the given callback function that is executed after the Renderer has transferred
  14118. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  14119. * the upload when attribute data are not needed anymore on the CPU side.
  14120. *
  14121. * @param {Function} callback - The `onUpload()` callback.
  14122. * @return {BufferAttribute} A reference to this instance.
  14123. */
  14124. onUpload( callback ) {
  14125. this.onUploadCallback = callback;
  14126. return this;
  14127. }
  14128. /**
  14129. * Returns a new buffer attribute with copied values from this instance.
  14130. *
  14131. * @return {BufferAttribute} A clone of this instance.
  14132. */
  14133. clone() {
  14134. return new this.constructor( this.array, this.itemSize ).copy( this );
  14135. }
  14136. /**
  14137. * Serializes the buffer attribute into JSON.
  14138. *
  14139. * @return {Object} A JSON object representing the serialized buffer attribute.
  14140. */
  14141. toJSON() {
  14142. const data = {
  14143. itemSize: this.itemSize,
  14144. type: this.array.constructor.name,
  14145. array: Array.from( this.array ),
  14146. normalized: this.normalized
  14147. };
  14148. if ( this.name !== '' ) data.name = this.name;
  14149. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  14150. return data;
  14151. }
  14152. }
  14153. /**
  14154. * Convenient class that can be used when creating a `Int8` buffer attribute with
  14155. * a plain `Array` instance.
  14156. *
  14157. * @augments BufferAttribute
  14158. */
  14159. class Int8BufferAttribute extends BufferAttribute {
  14160. /**
  14161. * Constructs a new buffer attribute.
  14162. *
  14163. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  14164. * @param {number} itemSize - The item size.
  14165. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14166. */
  14167. constructor( array, itemSize, normalized ) {
  14168. super( new Int8Array( array ), itemSize, normalized );
  14169. }
  14170. }
  14171. /**
  14172. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  14173. * a plain `Array` instance.
  14174. *
  14175. * @augments BufferAttribute
  14176. */
  14177. class Uint8BufferAttribute extends BufferAttribute {
  14178. /**
  14179. * Constructs a new buffer attribute.
  14180. *
  14181. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  14182. * @param {number} itemSize - The item size.
  14183. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14184. */
  14185. constructor( array, itemSize, normalized ) {
  14186. super( new Uint8Array( array ), itemSize, normalized );
  14187. }
  14188. }
  14189. /**
  14190. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  14191. * a plain `Array` instance.
  14192. *
  14193. * @augments BufferAttribute
  14194. */
  14195. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14196. /**
  14197. * Constructs a new buffer attribute.
  14198. *
  14199. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14200. * @param {number} itemSize - The item size.
  14201. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14202. */
  14203. constructor( array, itemSize, normalized ) {
  14204. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14205. }
  14206. }
  14207. /**
  14208. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14209. * a plain `Array` instance.
  14210. *
  14211. * @augments BufferAttribute
  14212. */
  14213. class Int16BufferAttribute extends BufferAttribute {
  14214. /**
  14215. * Constructs a new buffer attribute.
  14216. *
  14217. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14218. * @param {number} itemSize - The item size.
  14219. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14220. */
  14221. constructor( array, itemSize, normalized ) {
  14222. super( new Int16Array( array ), itemSize, normalized );
  14223. }
  14224. }
  14225. /**
  14226. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14227. * a plain `Array` instance.
  14228. *
  14229. * @augments BufferAttribute
  14230. */
  14231. class Uint16BufferAttribute extends BufferAttribute {
  14232. /**
  14233. * Constructs a new buffer attribute.
  14234. *
  14235. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14236. * @param {number} itemSize - The item size.
  14237. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14238. */
  14239. constructor( array, itemSize, normalized ) {
  14240. super( new Uint16Array( array ), itemSize, normalized );
  14241. }
  14242. }
  14243. /**
  14244. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14245. * a plain `Array` instance.
  14246. *
  14247. * @augments BufferAttribute
  14248. */
  14249. class Int32BufferAttribute extends BufferAttribute {
  14250. /**
  14251. * Constructs a new buffer attribute.
  14252. *
  14253. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14254. * @param {number} itemSize - The item size.
  14255. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14256. */
  14257. constructor( array, itemSize, normalized ) {
  14258. super( new Int32Array( array ), itemSize, normalized );
  14259. }
  14260. }
  14261. /**
  14262. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14263. * a plain `Array` instance.
  14264. *
  14265. * @augments BufferAttribute
  14266. */
  14267. class Uint32BufferAttribute extends BufferAttribute {
  14268. /**
  14269. * Constructs a new buffer attribute.
  14270. *
  14271. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14272. * @param {number} itemSize - The item size.
  14273. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14274. */
  14275. constructor( array, itemSize, normalized ) {
  14276. super( new Uint32Array( array ), itemSize, normalized );
  14277. }
  14278. }
  14279. /**
  14280. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14281. * a plain `Array` instance.
  14282. *
  14283. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14284. * browser support is still problematic.
  14285. *
  14286. * @augments BufferAttribute
  14287. */
  14288. class Float16BufferAttribute extends BufferAttribute {
  14289. /**
  14290. * Constructs a new buffer attribute.
  14291. *
  14292. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14293. * @param {number} itemSize - The item size.
  14294. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14295. */
  14296. constructor( array, itemSize, normalized ) {
  14297. super( new Uint16Array( array ), itemSize, normalized );
  14298. this.isFloat16BufferAttribute = true;
  14299. }
  14300. getX( index ) {
  14301. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14302. if ( this.normalized ) x = denormalize( x, this.array );
  14303. return x;
  14304. }
  14305. setX( index, x ) {
  14306. if ( this.normalized ) x = normalize( x, this.array );
  14307. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14308. return this;
  14309. }
  14310. getY( index ) {
  14311. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14312. if ( this.normalized ) y = denormalize( y, this.array );
  14313. return y;
  14314. }
  14315. setY( index, y ) {
  14316. if ( this.normalized ) y = normalize( y, this.array );
  14317. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14318. return this;
  14319. }
  14320. getZ( index ) {
  14321. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14322. if ( this.normalized ) z = denormalize( z, this.array );
  14323. return z;
  14324. }
  14325. setZ( index, z ) {
  14326. if ( this.normalized ) z = normalize( z, this.array );
  14327. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14328. return this;
  14329. }
  14330. getW( index ) {
  14331. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14332. if ( this.normalized ) w = denormalize( w, this.array );
  14333. return w;
  14334. }
  14335. setW( index, w ) {
  14336. if ( this.normalized ) w = normalize( w, this.array );
  14337. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14338. return this;
  14339. }
  14340. setXY( index, x, y ) {
  14341. index *= this.itemSize;
  14342. if ( this.normalized ) {
  14343. x = normalize( x, this.array );
  14344. y = normalize( y, this.array );
  14345. }
  14346. this.array[ index + 0 ] = toHalfFloat( x );
  14347. this.array[ index + 1 ] = toHalfFloat( y );
  14348. return this;
  14349. }
  14350. setXYZ( index, x, y, z ) {
  14351. index *= this.itemSize;
  14352. if ( this.normalized ) {
  14353. x = normalize( x, this.array );
  14354. y = normalize( y, this.array );
  14355. z = normalize( z, this.array );
  14356. }
  14357. this.array[ index + 0 ] = toHalfFloat( x );
  14358. this.array[ index + 1 ] = toHalfFloat( y );
  14359. this.array[ index + 2 ] = toHalfFloat( z );
  14360. return this;
  14361. }
  14362. setXYZW( index, x, y, z, w ) {
  14363. index *= this.itemSize;
  14364. if ( this.normalized ) {
  14365. x = normalize( x, this.array );
  14366. y = normalize( y, this.array );
  14367. z = normalize( z, this.array );
  14368. w = normalize( w, this.array );
  14369. }
  14370. this.array[ index + 0 ] = toHalfFloat( x );
  14371. this.array[ index + 1 ] = toHalfFloat( y );
  14372. this.array[ index + 2 ] = toHalfFloat( z );
  14373. this.array[ index + 3 ] = toHalfFloat( w );
  14374. return this;
  14375. }
  14376. }
  14377. /**
  14378. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14379. * a plain `Array` instance.
  14380. *
  14381. * @augments BufferAttribute
  14382. */
  14383. class Float32BufferAttribute extends BufferAttribute {
  14384. /**
  14385. * Constructs a new buffer attribute.
  14386. *
  14387. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14388. * @param {number} itemSize - The item size.
  14389. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14390. */
  14391. constructor( array, itemSize, normalized ) {
  14392. super( new Float32Array( array ), itemSize, normalized );
  14393. }
  14394. }
  14395. let _id$2 = 0;
  14396. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14397. const _obj = /*@__PURE__*/ new Object3D();
  14398. const _offset = /*@__PURE__*/ new Vector3();
  14399. const _box$2 = /*@__PURE__*/ new Box3();
  14400. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14401. const _vector$8 = /*@__PURE__*/ new Vector3();
  14402. /**
  14403. * A representation of mesh, line, or point geometry. Includes vertex
  14404. * positions, face indices, normals, colors, UVs, and custom attributes
  14405. * within buffers, reducing the cost of passing all this data to the GPU.
  14406. *
  14407. * ```js
  14408. * const geometry = new THREE.BufferGeometry();
  14409. * // create a simple square shape. We duplicate the top left and bottom right
  14410. * // vertices because each vertex needs to appear once per triangle.
  14411. * const vertices = new Float32Array( [
  14412. * -1.0, -1.0, 1.0, // v0
  14413. * 1.0, -1.0, 1.0, // v1
  14414. * 1.0, 1.0, 1.0, // v2
  14415. *
  14416. * 1.0, 1.0, 1.0, // v3
  14417. * -1.0, 1.0, 1.0, // v4
  14418. * -1.0, -1.0, 1.0 // v5
  14419. * ] );
  14420. * // itemSize = 3 because there are 3 values (components) per vertex
  14421. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14422. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14423. * const mesh = new THREE.Mesh( geometry, material );
  14424. * ```
  14425. *
  14426. * @augments EventDispatcher
  14427. */
  14428. class BufferGeometry extends EventDispatcher {
  14429. /**
  14430. * Constructs a new geometry.
  14431. */
  14432. constructor() {
  14433. super();
  14434. /**
  14435. * This flag can be used for type testing.
  14436. *
  14437. * @type {boolean}
  14438. * @readonly
  14439. * @default true
  14440. */
  14441. this.isBufferGeometry = true;
  14442. /**
  14443. * The ID of the geometry.
  14444. *
  14445. * @name BufferGeometry#id
  14446. * @type {number}
  14447. * @readonly
  14448. */
  14449. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14450. /**
  14451. * The UUID of the geometry.
  14452. *
  14453. * @type {string}
  14454. * @readonly
  14455. */
  14456. this.uuid = generateUUID();
  14457. /**
  14458. * The name of the geometry.
  14459. *
  14460. * @type {string}
  14461. */
  14462. this.name = '';
  14463. this.type = 'BufferGeometry';
  14464. /**
  14465. * Allows for vertices to be re-used across multiple triangles; this is
  14466. * called using "indexed triangles". Each triangle is associated with the
  14467. * indices of three vertices. This attribute therefore stores the index of
  14468. * each vertex for each triangular face. If this attribute is not set, the
  14469. * renderer assumes that each three contiguous positions represent a single triangle.
  14470. *
  14471. * @type {?BufferAttribute}
  14472. * @default null
  14473. */
  14474. this.index = null;
  14475. /**
  14476. * A (storage) buffer attribute which was generated with a compute shader and
  14477. * now defines indirect draw calls.
  14478. *
  14479. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14480. *
  14481. * @type {?BufferAttribute}
  14482. * @default null
  14483. */
  14484. this.indirect = null;
  14485. /**
  14486. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14487. *
  14488. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14489. *
  14490. * @type {number|Array<number>}
  14491. * @default 0
  14492. */
  14493. this.indirectOffset = 0;
  14494. /**
  14495. * This dictionary has as id the name of the attribute to be set and as value
  14496. * the buffer attribute to set it to. Rather than accessing this property directly,
  14497. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14498. *
  14499. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14500. */
  14501. this.attributes = {};
  14502. /**
  14503. * This dictionary holds the morph targets of the geometry.
  14504. *
  14505. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14506. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14507. *
  14508. * @type {Object}
  14509. */
  14510. this.morphAttributes = {};
  14511. /**
  14512. * Used to control the morph target behavior; when set to `true`, the morph
  14513. * target data is treated as relative offsets, rather than as absolute
  14514. * positions/normals.
  14515. *
  14516. * @type {boolean}
  14517. * @default false
  14518. */
  14519. this.morphTargetsRelative = false;
  14520. /**
  14521. * Split the geometry into groups, each of which will be rendered in a
  14522. * separate draw call. This allows an array of materials to be used with the geometry.
  14523. *
  14524. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14525. *
  14526. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14527. * indices, and must not leave vertices or indices unused.
  14528. *
  14529. * @type {Array<Object>}
  14530. */
  14531. this.groups = [];
  14532. /**
  14533. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14534. *
  14535. * @type {?Box3}
  14536. * @default null
  14537. */
  14538. this.boundingBox = null;
  14539. /**
  14540. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14541. *
  14542. * @type {?Sphere}
  14543. * @default null
  14544. */
  14545. this.boundingSphere = null;
  14546. /**
  14547. * Determines the part of the geometry to render. This should not be set directly,
  14548. * instead use `setDrawRange()`.
  14549. *
  14550. * @type {{start:number,count:number}}
  14551. */
  14552. this.drawRange = { start: 0, count: Infinity };
  14553. /**
  14554. * An object that can be used to store custom data about the geometry.
  14555. * It should not hold references to functions as these will not be cloned.
  14556. *
  14557. * @type {Object}
  14558. */
  14559. this.userData = {};
  14560. }
  14561. /**
  14562. * Returns the index of this geometry.
  14563. *
  14564. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14565. */
  14566. getIndex() {
  14567. return this.index;
  14568. }
  14569. /**
  14570. * Sets the given index to this geometry.
  14571. *
  14572. * @param {Array<number>|BufferAttribute} index - The index to set.
  14573. * @return {BufferGeometry} A reference to this instance.
  14574. */
  14575. setIndex( index ) {
  14576. if ( Array.isArray( index ) ) {
  14577. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14578. } else {
  14579. this.index = index;
  14580. }
  14581. return this;
  14582. }
  14583. /**
  14584. * Sets the given indirect attribute to this geometry.
  14585. *
  14586. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14587. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14588. * @return {BufferGeometry} A reference to this instance.
  14589. */
  14590. setIndirect( indirect, indirectOffset = 0 ) {
  14591. this.indirect = indirect;
  14592. this.indirectOffset = indirectOffset;
  14593. return this;
  14594. }
  14595. /**
  14596. * Returns the indirect attribute of this geometry.
  14597. *
  14598. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14599. */
  14600. getIndirect() {
  14601. return this.indirect;
  14602. }
  14603. /**
  14604. * Returns the buffer attribute for the given name.
  14605. *
  14606. * @param {string} name - The attribute name.
  14607. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14608. * Returns `undefined` if not attribute has been found.
  14609. */
  14610. getAttribute( name ) {
  14611. return this.attributes[ name ];
  14612. }
  14613. /**
  14614. * Sets the given attribute for the given name.
  14615. *
  14616. * @param {string} name - The attribute name.
  14617. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14618. * @return {BufferGeometry} A reference to this instance.
  14619. */
  14620. setAttribute( name, attribute ) {
  14621. this.attributes[ name ] = attribute;
  14622. return this;
  14623. }
  14624. /**
  14625. * Deletes the attribute for the given name.
  14626. *
  14627. * @param {string} name - The attribute name to delete.
  14628. * @return {BufferGeometry} A reference to this instance.
  14629. */
  14630. deleteAttribute( name ) {
  14631. delete this.attributes[ name ];
  14632. return this;
  14633. }
  14634. /**
  14635. * Returns `true` if this geometry has an attribute for the given name.
  14636. *
  14637. * @param {string} name - The attribute name.
  14638. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14639. */
  14640. hasAttribute( name ) {
  14641. return this.attributes[ name ] !== undefined;
  14642. }
  14643. /**
  14644. * Adds a group to this geometry.
  14645. *
  14646. * @param {number} start - The first element in this draw call. That is the first
  14647. * vertex for non-indexed geometry, otherwise the first triangle index.
  14648. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14649. * @param {number} [materialIndex=0] - The material array index to use.
  14650. */
  14651. addGroup( start, count, materialIndex = 0 ) {
  14652. this.groups.push( {
  14653. start: start,
  14654. count: count,
  14655. materialIndex: materialIndex
  14656. } );
  14657. }
  14658. /**
  14659. * Clears all groups.
  14660. */
  14661. clearGroups() {
  14662. this.groups = [];
  14663. }
  14664. /**
  14665. * Sets the draw range for this geometry.
  14666. *
  14667. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14668. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14669. * For indexed BufferGeometry, `count` is the number of indices to render.
  14670. */
  14671. setDrawRange( start, count ) {
  14672. this.drawRange.start = start;
  14673. this.drawRange.count = count;
  14674. }
  14675. /**
  14676. * Applies the given 4x4 transformation matrix to the geometry.
  14677. *
  14678. * @param {Matrix4} matrix - The matrix to apply.
  14679. * @return {BufferGeometry} A reference to this instance.
  14680. */
  14681. applyMatrix4( matrix ) {
  14682. const position = this.attributes.position;
  14683. if ( position !== undefined ) {
  14684. position.applyMatrix4( matrix );
  14685. position.needsUpdate = true;
  14686. }
  14687. const normal = this.attributes.normal;
  14688. if ( normal !== undefined ) {
  14689. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14690. normal.applyNormalMatrix( normalMatrix );
  14691. normal.needsUpdate = true;
  14692. }
  14693. const tangent = this.attributes.tangent;
  14694. if ( tangent !== undefined ) {
  14695. tangent.transformDirection( matrix );
  14696. tangent.needsUpdate = true;
  14697. }
  14698. if ( this.boundingBox !== null ) {
  14699. this.computeBoundingBox();
  14700. }
  14701. if ( this.boundingSphere !== null ) {
  14702. this.computeBoundingSphere();
  14703. }
  14704. return this;
  14705. }
  14706. /**
  14707. * Applies the rotation represented by the Quaternion to the geometry.
  14708. *
  14709. * @param {Quaternion} q - The Quaternion to apply.
  14710. * @return {BufferGeometry} A reference to this instance.
  14711. */
  14712. applyQuaternion( q ) {
  14713. _m1$2.makeRotationFromQuaternion( q );
  14714. this.applyMatrix4( _m1$2 );
  14715. return this;
  14716. }
  14717. /**
  14718. * Rotates the geometry about the X axis. This is typically done as a one time
  14719. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14720. * real-time mesh rotation.
  14721. *
  14722. * @param {number} angle - The angle in radians.
  14723. * @return {BufferGeometry} A reference to this instance.
  14724. */
  14725. rotateX( angle ) {
  14726. // rotate geometry around world x-axis
  14727. _m1$2.makeRotationX( angle );
  14728. this.applyMatrix4( _m1$2 );
  14729. return this;
  14730. }
  14731. /**
  14732. * Rotates the geometry about the Y axis. This is typically done as a one time
  14733. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14734. * real-time mesh rotation.
  14735. *
  14736. * @param {number} angle - The angle in radians.
  14737. * @return {BufferGeometry} A reference to this instance.
  14738. */
  14739. rotateY( angle ) {
  14740. // rotate geometry around world y-axis
  14741. _m1$2.makeRotationY( angle );
  14742. this.applyMatrix4( _m1$2 );
  14743. return this;
  14744. }
  14745. /**
  14746. * Rotates the geometry about the Z axis. This is typically done as a one time
  14747. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14748. * real-time mesh rotation.
  14749. *
  14750. * @param {number} angle - The angle in radians.
  14751. * @return {BufferGeometry} A reference to this instance.
  14752. */
  14753. rotateZ( angle ) {
  14754. // rotate geometry around world z-axis
  14755. _m1$2.makeRotationZ( angle );
  14756. this.applyMatrix4( _m1$2 );
  14757. return this;
  14758. }
  14759. /**
  14760. * Translates the geometry. This is typically done as a one time
  14761. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14762. * real-time mesh rotation.
  14763. *
  14764. * @param {number} x - The x offset.
  14765. * @param {number} y - The y offset.
  14766. * @param {number} z - The z offset.
  14767. * @return {BufferGeometry} A reference to this instance.
  14768. */
  14769. translate( x, y, z ) {
  14770. // translate geometry
  14771. _m1$2.makeTranslation( x, y, z );
  14772. this.applyMatrix4( _m1$2 );
  14773. return this;
  14774. }
  14775. /**
  14776. * Scales the geometry. This is typically done as a one time
  14777. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14778. * real-time mesh rotation.
  14779. *
  14780. * @param {number} x - The x scale.
  14781. * @param {number} y - The y scale.
  14782. * @param {number} z - The z scale.
  14783. * @return {BufferGeometry} A reference to this instance.
  14784. */
  14785. scale( x, y, z ) {
  14786. // scale geometry
  14787. _m1$2.makeScale( x, y, z );
  14788. this.applyMatrix4( _m1$2 );
  14789. return this;
  14790. }
  14791. /**
  14792. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14793. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14794. * real-time mesh rotation.
  14795. *
  14796. * @param {Vector3} vector - The target point.
  14797. * @return {BufferGeometry} A reference to this instance.
  14798. */
  14799. lookAt( vector ) {
  14800. _obj.lookAt( vector );
  14801. _obj.updateMatrix();
  14802. this.applyMatrix4( _obj.matrix );
  14803. return this;
  14804. }
  14805. /**
  14806. * Center the geometry based on its bounding box.
  14807. *
  14808. * @return {BufferGeometry} A reference to this instance.
  14809. */
  14810. center() {
  14811. this.computeBoundingBox();
  14812. this.boundingBox.getCenter( _offset ).negate();
  14813. this.translate( _offset.x, _offset.y, _offset.z );
  14814. return this;
  14815. }
  14816. /**
  14817. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14818. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14819. * set to `0`.
  14820. *
  14821. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14822. * data from the array. The length of the array must match the vertex count.
  14823. *
  14824. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14825. * @return {BufferGeometry} A reference to this instance.
  14826. */
  14827. setFromPoints( points ) {
  14828. const positionAttribute = this.getAttribute( 'position' );
  14829. if ( positionAttribute === undefined ) {
  14830. const position = [];
  14831. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14832. const point = points[ i ];
  14833. position.push( point.x, point.y, point.z || 0 );
  14834. }
  14835. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14836. } else {
  14837. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14838. for ( let i = 0; i < l; i ++ ) {
  14839. const point = points[ i ];
  14840. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14841. }
  14842. if ( points.length > positionAttribute.count ) {
  14843. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14844. }
  14845. positionAttribute.needsUpdate = true;
  14846. }
  14847. return this;
  14848. }
  14849. /**
  14850. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14851. * The bounding box is not computed by the engine; it must be computed by your app.
  14852. * You may need to recompute the bounding box if the geometry vertices are modified.
  14853. */
  14854. computeBoundingBox() {
  14855. if ( this.boundingBox === null ) {
  14856. this.boundingBox = new Box3();
  14857. }
  14858. const position = this.attributes.position;
  14859. const morphAttributesPosition = this.morphAttributes.position;
  14860. if ( position && position.isGLBufferAttribute ) {
  14861. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14862. this.boundingBox.set(
  14863. new Vector3( - Infinity, - Infinity, - Infinity ),
  14864. new Vector3( + Infinity, + Infinity, + Infinity )
  14865. );
  14866. return;
  14867. }
  14868. if ( position !== undefined ) {
  14869. this.boundingBox.setFromBufferAttribute( position );
  14870. // process morph attributes if present
  14871. if ( morphAttributesPosition ) {
  14872. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14873. const morphAttribute = morphAttributesPosition[ i ];
  14874. _box$2.setFromBufferAttribute( morphAttribute );
  14875. if ( this.morphTargetsRelative ) {
  14876. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14877. this.boundingBox.expandByPoint( _vector$8 );
  14878. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14879. this.boundingBox.expandByPoint( _vector$8 );
  14880. } else {
  14881. this.boundingBox.expandByPoint( _box$2.min );
  14882. this.boundingBox.expandByPoint( _box$2.max );
  14883. }
  14884. }
  14885. }
  14886. } else {
  14887. this.boundingBox.makeEmpty();
  14888. }
  14889. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14890. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14891. }
  14892. }
  14893. /**
  14894. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14895. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14896. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14897. */
  14898. computeBoundingSphere() {
  14899. if ( this.boundingSphere === null ) {
  14900. this.boundingSphere = new Sphere();
  14901. }
  14902. const position = this.attributes.position;
  14903. const morphAttributesPosition = this.morphAttributes.position;
  14904. if ( position && position.isGLBufferAttribute ) {
  14905. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14906. this.boundingSphere.set( new Vector3(), Infinity );
  14907. return;
  14908. }
  14909. if ( position ) {
  14910. // first, find the center of the bounding sphere
  14911. const center = this.boundingSphere.center;
  14912. _box$2.setFromBufferAttribute( position );
  14913. // process morph attributes if present
  14914. if ( morphAttributesPosition ) {
  14915. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14916. const morphAttribute = morphAttributesPosition[ i ];
  14917. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14918. if ( this.morphTargetsRelative ) {
  14919. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14920. _box$2.expandByPoint( _vector$8 );
  14921. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14922. _box$2.expandByPoint( _vector$8 );
  14923. } else {
  14924. _box$2.expandByPoint( _boxMorphTargets.min );
  14925. _box$2.expandByPoint( _boxMorphTargets.max );
  14926. }
  14927. }
  14928. }
  14929. _box$2.getCenter( center );
  14930. // second, try to find a boundingSphere with a radius smaller than the
  14931. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14932. let maxRadiusSq = 0;
  14933. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14934. _vector$8.fromBufferAttribute( position, i );
  14935. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14936. }
  14937. // process morph attributes if present
  14938. if ( morphAttributesPosition ) {
  14939. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14940. const morphAttribute = morphAttributesPosition[ i ];
  14941. const morphTargetsRelative = this.morphTargetsRelative;
  14942. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14943. _vector$8.fromBufferAttribute( morphAttribute, j );
  14944. if ( morphTargetsRelative ) {
  14945. _offset.fromBufferAttribute( position, j );
  14946. _vector$8.add( _offset );
  14947. }
  14948. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14949. }
  14950. }
  14951. }
  14952. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14953. if ( isNaN( this.boundingSphere.radius ) ) {
  14954. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14955. }
  14956. }
  14957. }
  14958. /**
  14959. * Calculates and adds a tangent attribute to this geometry.
  14960. *
  14961. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14962. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14963. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14964. */
  14965. computeTangents() {
  14966. const index = this.index;
  14967. const attributes = this.attributes;
  14968. // based on http://www.terathon.com/code/tangent.html
  14969. // (per vertex tangents)
  14970. if ( index === null ||
  14971. attributes.position === undefined ||
  14972. attributes.normal === undefined ||
  14973. attributes.uv === undefined ) {
  14974. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14975. return;
  14976. }
  14977. const positionAttribute = attributes.position;
  14978. const normalAttribute = attributes.normal;
  14979. const uvAttribute = attributes.uv;
  14980. if ( this.hasAttribute( 'tangent' ) === false ) {
  14981. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14982. }
  14983. const tangentAttribute = this.getAttribute( 'tangent' );
  14984. const tan1 = [], tan2 = [];
  14985. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14986. tan1[ i ] = new Vector3();
  14987. tan2[ i ] = new Vector3();
  14988. }
  14989. const vA = new Vector3(),
  14990. vB = new Vector3(),
  14991. vC = new Vector3(),
  14992. uvA = new Vector2(),
  14993. uvB = new Vector2(),
  14994. uvC = new Vector2(),
  14995. sdir = new Vector3(),
  14996. tdir = new Vector3();
  14997. function handleTriangle( a, b, c ) {
  14998. vA.fromBufferAttribute( positionAttribute, a );
  14999. vB.fromBufferAttribute( positionAttribute, b );
  15000. vC.fromBufferAttribute( positionAttribute, c );
  15001. uvA.fromBufferAttribute( uvAttribute, a );
  15002. uvB.fromBufferAttribute( uvAttribute, b );
  15003. uvC.fromBufferAttribute( uvAttribute, c );
  15004. vB.sub( vA );
  15005. vC.sub( vA );
  15006. uvB.sub( uvA );
  15007. uvC.sub( uvA );
  15008. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  15009. // silently ignore degenerate uv triangles having coincident or colinear vertices
  15010. if ( ! isFinite( r ) ) return;
  15011. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  15012. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  15013. tan1[ a ].add( sdir );
  15014. tan1[ b ].add( sdir );
  15015. tan1[ c ].add( sdir );
  15016. tan2[ a ].add( tdir );
  15017. tan2[ b ].add( tdir );
  15018. tan2[ c ].add( tdir );
  15019. }
  15020. let groups = this.groups;
  15021. if ( groups.length === 0 ) {
  15022. groups = [ {
  15023. start: 0,
  15024. count: index.count
  15025. } ];
  15026. }
  15027. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15028. const group = groups[ i ];
  15029. const start = group.start;
  15030. const count = group.count;
  15031. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15032. handleTriangle(
  15033. index.getX( j + 0 ),
  15034. index.getX( j + 1 ),
  15035. index.getX( j + 2 )
  15036. );
  15037. }
  15038. }
  15039. const tmp = new Vector3(), tmp2 = new Vector3();
  15040. const n = new Vector3(), n2 = new Vector3();
  15041. function handleVertex( v ) {
  15042. n.fromBufferAttribute( normalAttribute, v );
  15043. n2.copy( n );
  15044. const t = tan1[ v ];
  15045. // Gram-Schmidt orthogonalize
  15046. tmp.copy( t );
  15047. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  15048. // Calculate handedness
  15049. tmp2.crossVectors( n2, t );
  15050. const test = tmp2.dot( tan2[ v ] );
  15051. const w = ( test < 0.0 ) ? -1 : 1.0;
  15052. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  15053. }
  15054. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15055. const group = groups[ i ];
  15056. const start = group.start;
  15057. const count = group.count;
  15058. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15059. handleVertex( index.getX( j + 0 ) );
  15060. handleVertex( index.getX( j + 1 ) );
  15061. handleVertex( index.getX( j + 2 ) );
  15062. }
  15063. }
  15064. }
  15065. /**
  15066. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  15067. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  15068. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  15069. * to be the same as the face normal.
  15070. */
  15071. computeVertexNormals() {
  15072. const index = this.index;
  15073. const positionAttribute = this.getAttribute( 'position' );
  15074. if ( positionAttribute !== undefined ) {
  15075. let normalAttribute = this.getAttribute( 'normal' );
  15076. if ( normalAttribute === undefined ) {
  15077. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  15078. this.setAttribute( 'normal', normalAttribute );
  15079. } else {
  15080. // reset existing normals to zero
  15081. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  15082. normalAttribute.setXYZ( i, 0, 0, 0 );
  15083. }
  15084. }
  15085. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  15086. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  15087. const cb = new Vector3(), ab = new Vector3();
  15088. // indexed elements
  15089. if ( index ) {
  15090. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  15091. const vA = index.getX( i + 0 );
  15092. const vB = index.getX( i + 1 );
  15093. const vC = index.getX( i + 2 );
  15094. pA.fromBufferAttribute( positionAttribute, vA );
  15095. pB.fromBufferAttribute( positionAttribute, vB );
  15096. pC.fromBufferAttribute( positionAttribute, vC );
  15097. cb.subVectors( pC, pB );
  15098. ab.subVectors( pA, pB );
  15099. cb.cross( ab );
  15100. nA.fromBufferAttribute( normalAttribute, vA );
  15101. nB.fromBufferAttribute( normalAttribute, vB );
  15102. nC.fromBufferAttribute( normalAttribute, vC );
  15103. nA.add( cb );
  15104. nB.add( cb );
  15105. nC.add( cb );
  15106. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  15107. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  15108. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  15109. }
  15110. } else {
  15111. // non-indexed elements (unconnected triangle soup)
  15112. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  15113. pA.fromBufferAttribute( positionAttribute, i + 0 );
  15114. pB.fromBufferAttribute( positionAttribute, i + 1 );
  15115. pC.fromBufferAttribute( positionAttribute, i + 2 );
  15116. cb.subVectors( pC, pB );
  15117. ab.subVectors( pA, pB );
  15118. cb.cross( ab );
  15119. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  15120. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  15121. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  15122. }
  15123. }
  15124. this.normalizeNormals();
  15125. normalAttribute.needsUpdate = true;
  15126. }
  15127. }
  15128. /**
  15129. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  15130. * correct lighting on the geometry surfaces.
  15131. */
  15132. normalizeNormals() {
  15133. const normals = this.attributes.normal;
  15134. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  15135. _vector$8.fromBufferAttribute( normals, i );
  15136. _vector$8.normalize();
  15137. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  15138. }
  15139. }
  15140. /**
  15141. * Return a new non-index version of this indexed geometry. If the geometry
  15142. * is already non-indexed, the method is a NOOP.
  15143. *
  15144. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  15145. */
  15146. toNonIndexed() {
  15147. function convertBufferAttribute( attribute, indices ) {
  15148. const array = attribute.array;
  15149. const itemSize = attribute.itemSize;
  15150. const normalized = attribute.normalized;
  15151. const array2 = new array.constructor( indices.length * itemSize );
  15152. let index = 0, index2 = 0;
  15153. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  15154. if ( attribute.isInterleavedBufferAttribute ) {
  15155. index = indices[ i ] * attribute.data.stride + attribute.offset;
  15156. } else {
  15157. index = indices[ i ] * itemSize;
  15158. }
  15159. for ( let j = 0; j < itemSize; j ++ ) {
  15160. array2[ index2 ++ ] = array[ index ++ ];
  15161. }
  15162. }
  15163. return new BufferAttribute( array2, itemSize, normalized );
  15164. }
  15165. //
  15166. if ( this.index === null ) {
  15167. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  15168. return this;
  15169. }
  15170. const geometry2 = new BufferGeometry();
  15171. const indices = this.index.array;
  15172. const attributes = this.attributes;
  15173. // attributes
  15174. for ( const name in attributes ) {
  15175. const attribute = attributes[ name ];
  15176. const newAttribute = convertBufferAttribute( attribute, indices );
  15177. geometry2.setAttribute( name, newAttribute );
  15178. }
  15179. // morph attributes
  15180. const morphAttributes = this.morphAttributes;
  15181. for ( const name in morphAttributes ) {
  15182. const morphArray = [];
  15183. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15184. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  15185. const attribute = morphAttribute[ i ];
  15186. const newAttribute = convertBufferAttribute( attribute, indices );
  15187. morphArray.push( newAttribute );
  15188. }
  15189. geometry2.morphAttributes[ name ] = morphArray;
  15190. }
  15191. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  15192. // groups
  15193. const groups = this.groups;
  15194. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15195. const group = groups[ i ];
  15196. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15197. }
  15198. return geometry2;
  15199. }
  15200. /**
  15201. * Serializes the geometry into JSON.
  15202. *
  15203. * @return {Object} A JSON object representing the serialized geometry.
  15204. */
  15205. toJSON() {
  15206. const data = {
  15207. metadata: {
  15208. version: 4.7,
  15209. type: 'BufferGeometry',
  15210. generator: 'BufferGeometry.toJSON'
  15211. }
  15212. };
  15213. // standard BufferGeometry serialization
  15214. data.uuid = this.uuid;
  15215. data.type = this.type;
  15216. if ( this.name !== '' ) data.name = this.name;
  15217. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15218. if ( this.parameters !== undefined ) {
  15219. const parameters = this.parameters;
  15220. for ( const key in parameters ) {
  15221. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15222. }
  15223. return data;
  15224. }
  15225. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15226. data.data = { attributes: {} };
  15227. const index = this.index;
  15228. if ( index !== null ) {
  15229. data.data.index = {
  15230. type: index.array.constructor.name,
  15231. array: Array.prototype.slice.call( index.array )
  15232. };
  15233. }
  15234. const attributes = this.attributes;
  15235. for ( const key in attributes ) {
  15236. const attribute = attributes[ key ];
  15237. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15238. }
  15239. const morphAttributes = {};
  15240. let hasMorphAttributes = false;
  15241. for ( const key in this.morphAttributes ) {
  15242. const attributeArray = this.morphAttributes[ key ];
  15243. const array = [];
  15244. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15245. const attribute = attributeArray[ i ];
  15246. array.push( attribute.toJSON( data.data ) );
  15247. }
  15248. if ( array.length > 0 ) {
  15249. morphAttributes[ key ] = array;
  15250. hasMorphAttributes = true;
  15251. }
  15252. }
  15253. if ( hasMorphAttributes ) {
  15254. data.data.morphAttributes = morphAttributes;
  15255. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15256. }
  15257. const groups = this.groups;
  15258. if ( groups.length > 0 ) {
  15259. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15260. }
  15261. const boundingSphere = this.boundingSphere;
  15262. if ( boundingSphere !== null ) {
  15263. data.data.boundingSphere = boundingSphere.toJSON();
  15264. }
  15265. return data;
  15266. }
  15267. /**
  15268. * Returns a new geometry with copied values from this instance.
  15269. *
  15270. * @return {BufferGeometry} A clone of this instance.
  15271. */
  15272. clone() {
  15273. return new this.constructor().copy( this );
  15274. }
  15275. /**
  15276. * Copies the values of the given geometry to this instance.
  15277. *
  15278. * @param {BufferGeometry} source - The geometry to copy.
  15279. * @return {BufferGeometry} A reference to this instance.
  15280. */
  15281. copy( source ) {
  15282. // reset
  15283. this.index = null;
  15284. this.attributes = {};
  15285. this.morphAttributes = {};
  15286. this.groups = [];
  15287. this.boundingBox = null;
  15288. this.boundingSphere = null;
  15289. // used for storing cloned, shared data
  15290. const data = {};
  15291. // name
  15292. this.name = source.name;
  15293. // index
  15294. const index = source.index;
  15295. if ( index !== null ) {
  15296. this.setIndex( index.clone() );
  15297. }
  15298. // attributes
  15299. const attributes = source.attributes;
  15300. for ( const name in attributes ) {
  15301. const attribute = attributes[ name ];
  15302. this.setAttribute( name, attribute.clone( data ) );
  15303. }
  15304. // morph attributes
  15305. const morphAttributes = source.morphAttributes;
  15306. for ( const name in morphAttributes ) {
  15307. const array = [];
  15308. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15309. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15310. array.push( morphAttribute[ i ].clone( data ) );
  15311. }
  15312. this.morphAttributes[ name ] = array;
  15313. }
  15314. this.morphTargetsRelative = source.morphTargetsRelative;
  15315. // groups
  15316. const groups = source.groups;
  15317. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15318. const group = groups[ i ];
  15319. this.addGroup( group.start, group.count, group.materialIndex );
  15320. }
  15321. // bounding box
  15322. const boundingBox = source.boundingBox;
  15323. if ( boundingBox !== null ) {
  15324. this.boundingBox = boundingBox.clone();
  15325. }
  15326. // bounding sphere
  15327. const boundingSphere = source.boundingSphere;
  15328. if ( boundingSphere !== null ) {
  15329. this.boundingSphere = boundingSphere.clone();
  15330. }
  15331. // draw range
  15332. this.drawRange.start = source.drawRange.start;
  15333. this.drawRange.count = source.drawRange.count;
  15334. // user data
  15335. this.userData = source.userData;
  15336. return this;
  15337. }
  15338. /**
  15339. * Frees the GPU-related resources allocated by this instance. Call this
  15340. * method whenever this instance is no longer used in your app.
  15341. *
  15342. * @fires BufferGeometry#dispose
  15343. */
  15344. dispose() {
  15345. this.dispatchEvent( { type: 'dispose' } );
  15346. }
  15347. }
  15348. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15349. const _ray$3 = /*@__PURE__*/ new Ray();
  15350. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15351. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15352. const _vA$1 = /*@__PURE__*/ new Vector3();
  15353. const _vB$1 = /*@__PURE__*/ new Vector3();
  15354. const _vC$1 = /*@__PURE__*/ new Vector3();
  15355. const _tempA = /*@__PURE__*/ new Vector3();
  15356. const _morphA = /*@__PURE__*/ new Vector3();
  15357. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15358. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15359. /**
  15360. * Class representing triangular polygon mesh based objects.
  15361. *
  15362. * ```js
  15363. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15364. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15365. * const mesh = new THREE.Mesh( geometry, material );
  15366. * scene.add( mesh );
  15367. * ```
  15368. *
  15369. * @augments Object3D
  15370. */
  15371. class Mesh extends Object3D {
  15372. /**
  15373. * Constructs a new mesh.
  15374. *
  15375. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15376. * @param {Material|Array<Material>} [material] - The mesh material.
  15377. */
  15378. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15379. super();
  15380. /**
  15381. * This flag can be used for type testing.
  15382. *
  15383. * @type {boolean}
  15384. * @readonly
  15385. * @default true
  15386. */
  15387. this.isMesh = true;
  15388. this.type = 'Mesh';
  15389. /**
  15390. * The mesh geometry.
  15391. *
  15392. * @type {BufferGeometry}
  15393. */
  15394. this.geometry = geometry;
  15395. /**
  15396. * The mesh material.
  15397. *
  15398. * @type {Material|Array<Material>}
  15399. * @default MeshBasicMaterial
  15400. */
  15401. this.material = material;
  15402. /**
  15403. * A dictionary representing the morph targets in the geometry. The key is the
  15404. * morph targets name, the value its attribute index. This member is `undefined`
  15405. * by default and only set when morph targets are detected in the geometry.
  15406. *
  15407. * @type {Object<string,number>|undefined}
  15408. * @default undefined
  15409. */
  15410. this.morphTargetDictionary = undefined;
  15411. /**
  15412. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15413. * is applied. This member is `undefined` by default and only set when morph targets are
  15414. * detected in the geometry.
  15415. *
  15416. * @type {Array<number>|undefined}
  15417. * @default undefined
  15418. */
  15419. this.morphTargetInfluences = undefined;
  15420. /**
  15421. * The number of instances of this mesh.
  15422. * Can only be used with {@link WebGPURenderer}.
  15423. *
  15424. * @type {number}
  15425. * @default 1
  15426. */
  15427. this.count = 1;
  15428. this.updateMorphTargets();
  15429. }
  15430. copy( source, recursive ) {
  15431. super.copy( source, recursive );
  15432. if ( source.morphTargetInfluences !== undefined ) {
  15433. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15434. }
  15435. if ( source.morphTargetDictionary !== undefined ) {
  15436. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15437. }
  15438. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15439. this.geometry = source.geometry;
  15440. return this;
  15441. }
  15442. /**
  15443. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15444. * to make sure existing morph targets can influence this 3D object.
  15445. */
  15446. updateMorphTargets() {
  15447. const geometry = this.geometry;
  15448. const morphAttributes = geometry.morphAttributes;
  15449. const keys = Object.keys( morphAttributes );
  15450. if ( keys.length > 0 ) {
  15451. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15452. if ( morphAttribute !== undefined ) {
  15453. this.morphTargetInfluences = [];
  15454. this.morphTargetDictionary = {};
  15455. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15456. const name = morphAttribute[ m ].name || String( m );
  15457. this.morphTargetInfluences.push( 0 );
  15458. this.morphTargetDictionary[ name ] = m;
  15459. }
  15460. }
  15461. }
  15462. }
  15463. /**
  15464. * Returns the local-space position of the vertex at the given index, taking into
  15465. * account the current animation state of both morph targets and skinning.
  15466. *
  15467. * @param {number} index - The vertex index.
  15468. * @param {Vector3} target - The target object that is used to store the method's result.
  15469. * @return {Vector3} The vertex position in local space.
  15470. */
  15471. getVertexPosition( index, target ) {
  15472. const geometry = this.geometry;
  15473. const position = geometry.attributes.position;
  15474. const morphPosition = geometry.morphAttributes.position;
  15475. const morphTargetsRelative = geometry.morphTargetsRelative;
  15476. target.fromBufferAttribute( position, index );
  15477. const morphInfluences = this.morphTargetInfluences;
  15478. if ( morphPosition && morphInfluences ) {
  15479. _morphA.set( 0, 0, 0 );
  15480. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15481. const influence = morphInfluences[ i ];
  15482. const morphAttribute = morphPosition[ i ];
  15483. if ( influence === 0 ) continue;
  15484. _tempA.fromBufferAttribute( morphAttribute, index );
  15485. if ( morphTargetsRelative ) {
  15486. _morphA.addScaledVector( _tempA, influence );
  15487. } else {
  15488. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15489. }
  15490. }
  15491. target.add( _morphA );
  15492. }
  15493. return target;
  15494. }
  15495. /**
  15496. * Computes intersection points between a casted ray and this line.
  15497. *
  15498. * @param {Raycaster} raycaster - The raycaster.
  15499. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15500. */
  15501. raycast( raycaster, intersects ) {
  15502. const geometry = this.geometry;
  15503. const material = this.material;
  15504. const matrixWorld = this.matrixWorld;
  15505. if ( material === undefined ) return;
  15506. // test with bounding sphere in world space
  15507. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15508. _sphere$6.copy( geometry.boundingSphere );
  15509. _sphere$6.applyMatrix4( matrixWorld );
  15510. // check distance from ray origin to bounding sphere
  15511. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15512. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15513. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15514. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15515. }
  15516. // convert ray to local space of mesh
  15517. _inverseMatrix$3.copy( matrixWorld ).invert();
  15518. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15519. // test with bounding box in local space
  15520. if ( geometry.boundingBox !== null ) {
  15521. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15522. }
  15523. // test for intersections with geometry
  15524. this._computeIntersections( raycaster, intersects, _ray$3 );
  15525. }
  15526. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15527. let intersection;
  15528. const geometry = this.geometry;
  15529. const material = this.material;
  15530. const index = geometry.index;
  15531. const position = geometry.attributes.position;
  15532. const uv = geometry.attributes.uv;
  15533. const uv1 = geometry.attributes.uv1;
  15534. const normal = geometry.attributes.normal;
  15535. const groups = geometry.groups;
  15536. const drawRange = geometry.drawRange;
  15537. if ( index !== null ) {
  15538. // indexed buffer geometry
  15539. if ( Array.isArray( material ) ) {
  15540. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15541. const group = groups[ i ];
  15542. const groupMaterial = material[ group.materialIndex ];
  15543. const start = Math.max( group.start, drawRange.start );
  15544. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15545. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15546. const a = index.getX( j );
  15547. const b = index.getX( j + 1 );
  15548. const c = index.getX( j + 2 );
  15549. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15550. if ( intersection ) {
  15551. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15552. intersection.face.materialIndex = group.materialIndex;
  15553. intersects.push( intersection );
  15554. }
  15555. }
  15556. }
  15557. } else {
  15558. const start = Math.max( 0, drawRange.start );
  15559. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15560. for ( let i = start, il = end; i < il; i += 3 ) {
  15561. const a = index.getX( i );
  15562. const b = index.getX( i + 1 );
  15563. const c = index.getX( i + 2 );
  15564. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15565. if ( intersection ) {
  15566. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15567. intersects.push( intersection );
  15568. }
  15569. }
  15570. }
  15571. } else if ( position !== undefined ) {
  15572. // non-indexed buffer geometry
  15573. if ( Array.isArray( material ) ) {
  15574. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15575. const group = groups[ i ];
  15576. const groupMaterial = material[ group.materialIndex ];
  15577. const start = Math.max( group.start, drawRange.start );
  15578. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15579. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15580. const a = j;
  15581. const b = j + 1;
  15582. const c = j + 2;
  15583. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15584. if ( intersection ) {
  15585. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15586. intersection.face.materialIndex = group.materialIndex;
  15587. intersects.push( intersection );
  15588. }
  15589. }
  15590. }
  15591. } else {
  15592. const start = Math.max( 0, drawRange.start );
  15593. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15594. for ( let i = start, il = end; i < il; i += 3 ) {
  15595. const a = i;
  15596. const b = i + 1;
  15597. const c = i + 2;
  15598. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15599. if ( intersection ) {
  15600. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15601. intersects.push( intersection );
  15602. }
  15603. }
  15604. }
  15605. }
  15606. }
  15607. }
  15608. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15609. let intersect;
  15610. if ( material.side === BackSide ) {
  15611. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15612. } else {
  15613. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15614. }
  15615. if ( intersect === null ) return null;
  15616. _intersectionPointWorld.copy( point );
  15617. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15618. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15619. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15620. return {
  15621. distance: distance,
  15622. point: _intersectionPointWorld.clone(),
  15623. object: object
  15624. };
  15625. }
  15626. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15627. object.getVertexPosition( a, _vA$1 );
  15628. object.getVertexPosition( b, _vB$1 );
  15629. object.getVertexPosition( c, _vC$1 );
  15630. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15631. if ( intersection ) {
  15632. const barycoord = new Vector3();
  15633. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15634. if ( uv ) {
  15635. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15636. }
  15637. if ( uv1 ) {
  15638. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15639. }
  15640. if ( normal ) {
  15641. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15642. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15643. intersection.normal.multiplyScalar( -1 );
  15644. }
  15645. }
  15646. const face = {
  15647. a: a,
  15648. b: b,
  15649. c: c,
  15650. normal: new Vector3(),
  15651. materialIndex: 0
  15652. };
  15653. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15654. intersection.face = face;
  15655. intersection.barycoord = barycoord;
  15656. }
  15657. return intersection;
  15658. }
  15659. /**
  15660. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15661. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15662. * of the axes.
  15663. *
  15664. * ```js
  15665. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15666. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15667. * const cube = new THREE.Mesh( geometry, material );
  15668. * scene.add( cube );
  15669. * ```
  15670. *
  15671. * @augments BufferGeometry
  15672. * @demo scenes/geometry-browser.html#BoxGeometry
  15673. */
  15674. class BoxGeometry extends BufferGeometry {
  15675. /**
  15676. * Constructs a new box geometry.
  15677. *
  15678. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15679. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15680. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15681. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15682. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15683. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15684. */
  15685. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15686. super();
  15687. this.type = 'BoxGeometry';
  15688. /**
  15689. * Holds the constructor parameters that have been
  15690. * used to generate the geometry. Any modification
  15691. * after instantiation does not change the geometry.
  15692. *
  15693. * @type {Object}
  15694. */
  15695. this.parameters = {
  15696. width: width,
  15697. height: height,
  15698. depth: depth,
  15699. widthSegments: widthSegments,
  15700. heightSegments: heightSegments,
  15701. depthSegments: depthSegments
  15702. };
  15703. const scope = this;
  15704. // segments
  15705. widthSegments = Math.floor( widthSegments );
  15706. heightSegments = Math.floor( heightSegments );
  15707. depthSegments = Math.floor( depthSegments );
  15708. // buffers
  15709. const indices = [];
  15710. const vertices = [];
  15711. const normals = [];
  15712. const uvs = [];
  15713. // helper variables
  15714. let numberOfVertices = 0;
  15715. let groupStart = 0;
  15716. // build each side of the box geometry
  15717. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15718. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15719. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15720. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15721. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15722. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15723. // build geometry
  15724. this.setIndex( indices );
  15725. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15726. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15727. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15728. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15729. const segmentWidth = width / gridX;
  15730. const segmentHeight = height / gridY;
  15731. const widthHalf = width / 2;
  15732. const heightHalf = height / 2;
  15733. const depthHalf = depth / 2;
  15734. const gridX1 = gridX + 1;
  15735. const gridY1 = gridY + 1;
  15736. let vertexCounter = 0;
  15737. let groupCount = 0;
  15738. const vector = new Vector3();
  15739. // generate vertices, normals and uvs
  15740. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15741. const y = iy * segmentHeight - heightHalf;
  15742. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15743. const x = ix * segmentWidth - widthHalf;
  15744. // set values to correct vector component
  15745. vector[ u ] = x * udir;
  15746. vector[ v ] = y * vdir;
  15747. vector[ w ] = depthHalf;
  15748. // now apply vector to vertex buffer
  15749. vertices.push( vector.x, vector.y, vector.z );
  15750. // set values to correct vector component
  15751. vector[ u ] = 0;
  15752. vector[ v ] = 0;
  15753. vector[ w ] = depth > 0 ? 1 : -1;
  15754. // now apply vector to normal buffer
  15755. normals.push( vector.x, vector.y, vector.z );
  15756. // uvs
  15757. uvs.push( ix / gridX );
  15758. uvs.push( 1 - ( iy / gridY ) );
  15759. // counters
  15760. vertexCounter += 1;
  15761. }
  15762. }
  15763. // indices
  15764. // 1. you need three indices to draw a single face
  15765. // 2. a single segment consists of two faces
  15766. // 3. so we need to generate six (2*3) indices per segment
  15767. for ( let iy = 0; iy < gridY; iy ++ ) {
  15768. for ( let ix = 0; ix < gridX; ix ++ ) {
  15769. const a = numberOfVertices + ix + gridX1 * iy;
  15770. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15771. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15772. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15773. // faces
  15774. indices.push( a, b, d );
  15775. indices.push( b, c, d );
  15776. // increase counter
  15777. groupCount += 6;
  15778. }
  15779. }
  15780. // add a group to the geometry. this will ensure multi material support
  15781. scope.addGroup( groupStart, groupCount, materialIndex );
  15782. // calculate new start value for groups
  15783. groupStart += groupCount;
  15784. // update total number of vertices
  15785. numberOfVertices += vertexCounter;
  15786. }
  15787. }
  15788. copy( source ) {
  15789. super.copy( source );
  15790. this.parameters = Object.assign( {}, source.parameters );
  15791. return this;
  15792. }
  15793. /**
  15794. * Factory method for creating an instance of this class from the given
  15795. * JSON object.
  15796. *
  15797. * @param {Object} data - A JSON object representing the serialized geometry.
  15798. * @return {BoxGeometry} A new instance.
  15799. */
  15800. static fromJSON( data ) {
  15801. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15802. }
  15803. }
  15804. /**
  15805. * Provides utility functions for managing uniforms.
  15806. *
  15807. * @module UniformsUtils
  15808. */
  15809. /**
  15810. * Clones the given uniform definitions by performing a deep-copy. That means
  15811. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15812. * the cloned uniform will refer to a new object reference.
  15813. *
  15814. * @param {Object} src - An object representing uniform definitions.
  15815. * @return {Object} The cloned uniforms.
  15816. */
  15817. function cloneUniforms( src ) {
  15818. const dst = {};
  15819. for ( const u in src ) {
  15820. dst[ u ] = {};
  15821. for ( const p in src[ u ] ) {
  15822. const property = src[ u ][ p ];
  15823. if ( property && ( property.isColor ||
  15824. property.isMatrix3 || property.isMatrix4 ||
  15825. property.isVector2 || property.isVector3 || property.isVector4 ||
  15826. property.isTexture || property.isQuaternion ) ) {
  15827. if ( property.isRenderTargetTexture ) {
  15828. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15829. dst[ u ][ p ] = null;
  15830. } else {
  15831. dst[ u ][ p ] = property.clone();
  15832. }
  15833. } else if ( Array.isArray( property ) ) {
  15834. dst[ u ][ p ] = property.slice();
  15835. } else {
  15836. dst[ u ][ p ] = property;
  15837. }
  15838. }
  15839. }
  15840. return dst;
  15841. }
  15842. /**
  15843. * Merges the given uniform definitions into a single object. Since the
  15844. * method internally uses cloneUniforms(), it performs a deep-copy when
  15845. * producing the merged uniform definitions.
  15846. *
  15847. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15848. * @return {Object} The merged uniforms.
  15849. */
  15850. function mergeUniforms( uniforms ) {
  15851. const merged = {};
  15852. for ( let u = 0; u < uniforms.length; u ++ ) {
  15853. const tmp = cloneUniforms( uniforms[ u ] );
  15854. for ( const p in tmp ) {
  15855. merged[ p ] = tmp[ p ];
  15856. }
  15857. }
  15858. return merged;
  15859. }
  15860. function cloneUniformsGroups( src ) {
  15861. const dst = [];
  15862. for ( let u = 0; u < src.length; u ++ ) {
  15863. dst.push( src[ u ].clone() );
  15864. }
  15865. return dst;
  15866. }
  15867. function getUnlitUniformColorSpace( renderer ) {
  15868. const currentRenderTarget = renderer.getRenderTarget();
  15869. if ( currentRenderTarget === null ) {
  15870. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15871. return renderer.outputColorSpace;
  15872. }
  15873. // https://github.com/mrdoob/three.js/issues/27868
  15874. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15875. return currentRenderTarget.texture.colorSpace;
  15876. }
  15877. return ColorManagement.workingColorSpace;
  15878. }
  15879. // Legacy
  15880. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15881. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15882. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15883. /**
  15884. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15885. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15886. * effect not included with any of the built-in materials.
  15887. *
  15888. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15889. *
  15890. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15891. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15892. * you don't want that, use {@link RawShaderMaterial} instead.
  15893. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15894. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15895. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15896. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15897. * - The loop variable has to be *i*.
  15898. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15899. * value of *i* for the given iteration and can be used in preprocessor
  15900. * statements.
  15901. *
  15902. * ```js
  15903. * const material = new THREE.ShaderMaterial( {
  15904. * uniforms: {
  15905. * time: { value: 1.0 },
  15906. * resolution: { value: new THREE.Vector2() }
  15907. * },
  15908. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15909. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15910. * } );
  15911. * ```
  15912. *
  15913. * @augments Material
  15914. */
  15915. class ShaderMaterial extends Material {
  15916. /**
  15917. * Constructs a new shader material.
  15918. *
  15919. * @param {Object} [parameters] - An object with one or more properties
  15920. * defining the material's appearance. Any property of the material
  15921. * (including any property from inherited materials) can be passed
  15922. * in here. Color values can be passed any type of value accepted
  15923. * by {@link Color#set}.
  15924. */
  15925. constructor( parameters ) {
  15926. super();
  15927. /**
  15928. * This flag can be used for type testing.
  15929. *
  15930. * @type {boolean}
  15931. * @readonly
  15932. * @default true
  15933. */
  15934. this.isShaderMaterial = true;
  15935. this.type = 'ShaderMaterial';
  15936. /**
  15937. * Defines custom constants using `#define` directives within the GLSL code
  15938. * for both the vertex shader and the fragment shader; each key/value pair
  15939. * yields another directive.
  15940. * ```js
  15941. * defines: {
  15942. * FOO: 15,
  15943. * BAR: true
  15944. * }
  15945. * ```
  15946. * Yields the lines:
  15947. * ```
  15948. * #define FOO 15
  15949. * #define BAR true
  15950. * ```
  15951. *
  15952. * @type {Object}
  15953. */
  15954. this.defines = {};
  15955. /**
  15956. * An object of the form:
  15957. * ```js
  15958. * {
  15959. * "uniform1": { value: 1.0 },
  15960. * "uniform2": { value: 2 }
  15961. * }
  15962. * ```
  15963. * specifying the uniforms to be passed to the shader code; keys are uniform
  15964. * names, values are definitions of the form
  15965. * ```
  15966. * {
  15967. * value: 1.0
  15968. * }
  15969. * ```
  15970. * where `value` is the value of the uniform. Names must match the name of
  15971. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15972. * on every frame, so updating the value of the uniform will immediately
  15973. * update the value available to the GLSL code.
  15974. *
  15975. * @type {Object}
  15976. */
  15977. this.uniforms = {};
  15978. /**
  15979. * An array holding uniforms groups for configuring UBOs.
  15980. *
  15981. * @type {Array<UniformsGroup>}
  15982. */
  15983. this.uniformsGroups = [];
  15984. /**
  15985. * Vertex shader GLSL code. This is the actual code for the shader.
  15986. *
  15987. * @type {string}
  15988. */
  15989. this.vertexShader = default_vertex;
  15990. /**
  15991. * Fragment shader GLSL code. This is the actual code for the shader.
  15992. *
  15993. * @type {string}
  15994. */
  15995. this.fragmentShader = default_fragment;
  15996. /**
  15997. * Controls line thickness or lines.
  15998. *
  15999. * WebGL and WebGPU ignore this setting and always render line primitives with a
  16000. * width of one pixel.
  16001. *
  16002. * @type {number}
  16003. * @default 1
  16004. */
  16005. this.linewidth = 1;
  16006. /**
  16007. * Renders the geometry as a wireframe.
  16008. *
  16009. * @type {boolean}
  16010. * @default false
  16011. */
  16012. this.wireframe = false;
  16013. /**
  16014. * Controls the thickness of the wireframe.
  16015. *
  16016. * WebGL and WebGPU ignore this property and always render
  16017. * 1 pixel wide lines.
  16018. *
  16019. * @type {number}
  16020. * @default 1
  16021. */
  16022. this.wireframeLinewidth = 1;
  16023. /**
  16024. * Defines whether the material color is affected by global fog settings; `true`
  16025. * to pass fog uniforms to the shader.
  16026. *
  16027. * Setting this property to `true` requires the definition of fog uniforms. It is
  16028. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  16029. * with predefined fog uniforms.
  16030. *
  16031. * ```js
  16032. * const material = new ShaderMaterial( {
  16033. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  16034. * vertexShader: vertexShader,
  16035. * fragmentShader: fragmentShader,
  16036. * fog: true
  16037. * } );
  16038. * ```
  16039. *
  16040. * @type {boolean}
  16041. * @default false
  16042. */
  16043. this.fog = false;
  16044. /**
  16045. * Defines whether this material uses lighting; `true` to pass uniform data
  16046. * related to lighting to this shader.
  16047. *
  16048. * @type {boolean}
  16049. * @default false
  16050. */
  16051. this.lights = false;
  16052. /**
  16053. * Defines whether this material supports clipping; `true` to let the renderer
  16054. * pass the clippingPlanes uniform.
  16055. *
  16056. * @type {boolean}
  16057. * @default false
  16058. */
  16059. this.clipping = false;
  16060. /**
  16061. * Overwritten and set to `true` by default.
  16062. *
  16063. * @type {boolean}
  16064. * @default true
  16065. */
  16066. this.forceSinglePass = true;
  16067. /**
  16068. * This object allows to enable certain WebGL 2 extensions.
  16069. *
  16070. * - clipCullDistance: set to `true` to use vertex shader clipping
  16071. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  16072. *
  16073. * @type {{clipCullDistance:false,multiDraw:false}}
  16074. */
  16075. this.extensions = {
  16076. clipCullDistance: false, // set to use vertex shader clipping
  16077. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  16078. };
  16079. /**
  16080. * When the rendered geometry doesn't include these attributes but the
  16081. * material does, these default values will be passed to the shaders. This
  16082. * avoids errors when buffer data is missing.
  16083. *
  16084. * - color: [ 1, 1, 1 ]
  16085. * - uv: [ 0, 0 ]
  16086. * - uv1: [ 0, 0 ]
  16087. *
  16088. * @type {Object}
  16089. */
  16090. this.defaultAttributeValues = {
  16091. 'color': [ 1, 1, 1 ],
  16092. 'uv': [ 0, 0 ],
  16093. 'uv1': [ 0, 0 ]
  16094. };
  16095. /**
  16096. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  16097. * to bind a generic vertex index to an attribute variable.
  16098. *
  16099. * @type {string|undefined}
  16100. * @default undefined
  16101. */
  16102. this.index0AttributeName = undefined;
  16103. /**
  16104. * Can be used to force a uniform update while changing uniforms in
  16105. * {@link Object3D#onBeforeRender}.
  16106. *
  16107. * @type {boolean}
  16108. * @default false
  16109. */
  16110. this.uniformsNeedUpdate = false;
  16111. /**
  16112. * Defines the GLSL version of custom shader code.
  16113. *
  16114. * @type {?(GLSL1|GLSL3)}
  16115. * @default null
  16116. */
  16117. this.glslVersion = null;
  16118. if ( parameters !== undefined ) {
  16119. this.setValues( parameters );
  16120. }
  16121. }
  16122. copy( source ) {
  16123. super.copy( source );
  16124. this.fragmentShader = source.fragmentShader;
  16125. this.vertexShader = source.vertexShader;
  16126. this.uniforms = cloneUniforms( source.uniforms );
  16127. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  16128. this.defines = Object.assign( {}, source.defines );
  16129. this.wireframe = source.wireframe;
  16130. this.wireframeLinewidth = source.wireframeLinewidth;
  16131. this.fog = source.fog;
  16132. this.lights = source.lights;
  16133. this.clipping = source.clipping;
  16134. this.extensions = Object.assign( {}, source.extensions );
  16135. this.glslVersion = source.glslVersion;
  16136. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  16137. this.index0AttributeName = source.index0AttributeName;
  16138. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  16139. return this;
  16140. }
  16141. toJSON( meta ) {
  16142. const data = super.toJSON( meta );
  16143. data.glslVersion = this.glslVersion;
  16144. data.uniforms = {};
  16145. for ( const name in this.uniforms ) {
  16146. const uniform = this.uniforms[ name ];
  16147. const value = uniform.value;
  16148. if ( value && value.isTexture ) {
  16149. data.uniforms[ name ] = {
  16150. type: 't',
  16151. value: value.toJSON( meta ).uuid
  16152. };
  16153. } else if ( value && value.isColor ) {
  16154. data.uniforms[ name ] = {
  16155. type: 'c',
  16156. value: value.getHex()
  16157. };
  16158. } else if ( value && value.isVector2 ) {
  16159. data.uniforms[ name ] = {
  16160. type: 'v2',
  16161. value: value.toArray()
  16162. };
  16163. } else if ( value && value.isVector3 ) {
  16164. data.uniforms[ name ] = {
  16165. type: 'v3',
  16166. value: value.toArray()
  16167. };
  16168. } else if ( value && value.isVector4 ) {
  16169. data.uniforms[ name ] = {
  16170. type: 'v4',
  16171. value: value.toArray()
  16172. };
  16173. } else if ( value && value.isMatrix3 ) {
  16174. data.uniforms[ name ] = {
  16175. type: 'm3',
  16176. value: value.toArray()
  16177. };
  16178. } else if ( value && value.isMatrix4 ) {
  16179. data.uniforms[ name ] = {
  16180. type: 'm4',
  16181. value: value.toArray()
  16182. };
  16183. } else {
  16184. data.uniforms[ name ] = {
  16185. value: value
  16186. };
  16187. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  16188. }
  16189. }
  16190. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  16191. data.vertexShader = this.vertexShader;
  16192. data.fragmentShader = this.fragmentShader;
  16193. data.lights = this.lights;
  16194. data.clipping = this.clipping;
  16195. const extensions = {};
  16196. for ( const key in this.extensions ) {
  16197. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16198. }
  16199. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16200. return data;
  16201. }
  16202. }
  16203. const _position$3 = /*@__PURE__*/ new Vector3();
  16204. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  16205. const _scale$2 = /*@__PURE__*/ new Vector3();
  16206. /**
  16207. * Abstract base class for cameras. This class should always be inherited
  16208. * when you build a new camera.
  16209. *
  16210. * @abstract
  16211. * @augments Object3D
  16212. */
  16213. class Camera extends Object3D {
  16214. /**
  16215. * Constructs a new camera.
  16216. */
  16217. constructor() {
  16218. super();
  16219. /**
  16220. * This flag can be used for type testing.
  16221. *
  16222. * @type {boolean}
  16223. * @readonly
  16224. * @default true
  16225. */
  16226. this.isCamera = true;
  16227. this.type = 'Camera';
  16228. /**
  16229. * The inverse of the camera's world matrix.
  16230. *
  16231. * @type {Matrix4}
  16232. */
  16233. this.matrixWorldInverse = new Matrix4();
  16234. /**
  16235. * The camera's projection matrix.
  16236. *
  16237. * @type {Matrix4}
  16238. */
  16239. this.projectionMatrix = new Matrix4();
  16240. /**
  16241. * The inverse of the camera's projection matrix.
  16242. *
  16243. * @type {Matrix4}
  16244. */
  16245. this.projectionMatrixInverse = new Matrix4();
  16246. /**
  16247. * The coordinate system in which the camera is used.
  16248. *
  16249. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16250. */
  16251. this.coordinateSystem = WebGLCoordinateSystem;
  16252. this._reversedDepth = false;
  16253. }
  16254. /**
  16255. * The flag that indicates whether the camera uses a reversed depth buffer.
  16256. *
  16257. * @type {boolean}
  16258. * @default false
  16259. */
  16260. get reversedDepth() {
  16261. return this._reversedDepth;
  16262. }
  16263. copy( source, recursive ) {
  16264. super.copy( source, recursive );
  16265. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16266. this.projectionMatrix.copy( source.projectionMatrix );
  16267. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16268. this.coordinateSystem = source.coordinateSystem;
  16269. return this;
  16270. }
  16271. /**
  16272. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16273. *
  16274. * This method is overwritten since cameras have a different forward vector compared to other
  16275. * 3D objects. A camera looks down its local, negative z-axis by default.
  16276. *
  16277. * @param {Vector3} target - The target vector the result is stored to.
  16278. * @return {Vector3} The 3D object's direction in world space.
  16279. */
  16280. getWorldDirection( target ) {
  16281. return super.getWorldDirection( target ).negate();
  16282. }
  16283. updateMatrixWorld( force ) {
  16284. super.updateMatrixWorld( force );
  16285. // exclude scale from view matrix to be glTF conform
  16286. this.matrixWorld.decompose( _position$3, _quaternion$2, _scale$2 );
  16287. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  16288. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16289. } else {
  16290. this.matrixWorldInverse.compose( _position$3, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  16291. }
  16292. }
  16293. updateWorldMatrix( updateParents, updateChildren ) {
  16294. super.updateWorldMatrix( updateParents, updateChildren );
  16295. // exclude scale from view matrix to be glTF conform
  16296. this.matrixWorld.decompose( _position$3, _quaternion$2, _scale$2 );
  16297. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  16298. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16299. } else {
  16300. this.matrixWorldInverse.compose( _position$3, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  16301. }
  16302. }
  16303. clone() {
  16304. return new this.constructor().copy( this );
  16305. }
  16306. }
  16307. const _v3$1 = /*@__PURE__*/ new Vector3();
  16308. const _minTarget = /*@__PURE__*/ new Vector2();
  16309. const _maxTarget = /*@__PURE__*/ new Vector2();
  16310. /**
  16311. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16312. *
  16313. * This projection mode is designed to mimic the way the human eye sees. It
  16314. * is the most common projection mode used for rendering a 3D scene.
  16315. *
  16316. * ```js
  16317. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16318. * scene.add( camera );
  16319. * ```
  16320. *
  16321. * @augments Camera
  16322. */
  16323. class PerspectiveCamera extends Camera {
  16324. /**
  16325. * Constructs a new perspective camera.
  16326. *
  16327. * @param {number} [fov=50] - The vertical field of view.
  16328. * @param {number} [aspect=1] - The aspect ratio.
  16329. * @param {number} [near=0.1] - The camera's near plane.
  16330. * @param {number} [far=2000] - The camera's far plane.
  16331. */
  16332. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16333. super();
  16334. /**
  16335. * This flag can be used for type testing.
  16336. *
  16337. * @type {boolean}
  16338. * @readonly
  16339. * @default true
  16340. */
  16341. this.isPerspectiveCamera = true;
  16342. this.type = 'PerspectiveCamera';
  16343. /**
  16344. * The vertical field of view, from bottom to top of view,
  16345. * in degrees.
  16346. *
  16347. * @type {number}
  16348. * @default 50
  16349. */
  16350. this.fov = fov;
  16351. /**
  16352. * The zoom factor of the camera.
  16353. *
  16354. * @type {number}
  16355. * @default 1
  16356. */
  16357. this.zoom = 1;
  16358. /**
  16359. * The camera's near plane. The valid range is greater than `0`
  16360. * and less than the current value of {@link PerspectiveCamera#far}.
  16361. *
  16362. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16363. * valid value for a perspective camera's near plane.
  16364. *
  16365. * @type {number}
  16366. * @default 0.1
  16367. */
  16368. this.near = near;
  16369. /**
  16370. * The camera's far plane. Must be greater than the
  16371. * current value of {@link PerspectiveCamera#near}.
  16372. *
  16373. * @type {number}
  16374. * @default 2000
  16375. */
  16376. this.far = far;
  16377. /**
  16378. * Object distance used for stereoscopy and depth-of-field effects. This
  16379. * parameter does not influence the projection matrix unless a
  16380. * {@link StereoCamera} is being used.
  16381. *
  16382. * @type {number}
  16383. * @default 10
  16384. */
  16385. this.focus = 10;
  16386. /**
  16387. * The aspect ratio, usually the canvas width / canvas height.
  16388. *
  16389. * @type {number}
  16390. * @default 1
  16391. */
  16392. this.aspect = aspect;
  16393. /**
  16394. * Represents the frustum window specification. This property should not be edited
  16395. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16396. *
  16397. * @type {?Object}
  16398. * @default null
  16399. */
  16400. this.view = null;
  16401. /**
  16402. * Film size used for the larger axis. Default is `35` (millimeters). This
  16403. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16404. * is set to a nonzero value.
  16405. *
  16406. * @type {number}
  16407. * @default 35
  16408. */
  16409. this.filmGauge = 35;
  16410. /**
  16411. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16412. *
  16413. * @type {number}
  16414. * @default 0
  16415. */
  16416. this.filmOffset = 0;
  16417. this.updateProjectionMatrix();
  16418. }
  16419. copy( source, recursive ) {
  16420. super.copy( source, recursive );
  16421. this.fov = source.fov;
  16422. this.zoom = source.zoom;
  16423. this.near = source.near;
  16424. this.far = source.far;
  16425. this.focus = source.focus;
  16426. this.aspect = source.aspect;
  16427. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16428. this.filmGauge = source.filmGauge;
  16429. this.filmOffset = source.filmOffset;
  16430. return this;
  16431. }
  16432. /**
  16433. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16434. *
  16435. * The default film gauge is 35, so that the focal length can be specified for
  16436. * a 35mm (full frame) camera.
  16437. *
  16438. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16439. */
  16440. setFocalLength( focalLength ) {
  16441. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16442. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16443. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16444. this.updateProjectionMatrix();
  16445. }
  16446. /**
  16447. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16448. * {@link PerspectiveCamera#filmGauge}.
  16449. *
  16450. * @return {number} The computed focal length.
  16451. */
  16452. getFocalLength() {
  16453. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16454. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16455. }
  16456. /**
  16457. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16458. *
  16459. * @return {number} The effective FOV.
  16460. */
  16461. getEffectiveFOV() {
  16462. return RAD2DEG * 2 * Math.atan(
  16463. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16464. }
  16465. /**
  16466. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16467. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16468. *
  16469. * @return {number} The film width.
  16470. */
  16471. getFilmWidth() {
  16472. // film not completely covered in portrait format (aspect < 1)
  16473. return this.filmGauge * Math.min( this.aspect, 1 );
  16474. }
  16475. /**
  16476. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16477. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16478. *
  16479. * @return {number} The film width.
  16480. */
  16481. getFilmHeight() {
  16482. // film not completely covered in landscape format (aspect > 1)
  16483. return this.filmGauge / Math.max( this.aspect, 1 );
  16484. }
  16485. /**
  16486. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16487. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16488. *
  16489. * @param {number} distance - The viewing distance.
  16490. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16491. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16492. */
  16493. getViewBounds( distance, minTarget, maxTarget ) {
  16494. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16495. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16496. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16497. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16498. }
  16499. /**
  16500. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16501. *
  16502. * @param {number} distance - The viewing distance.
  16503. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16504. * @returns {Vector2} The view size.
  16505. */
  16506. getViewSize( distance, target ) {
  16507. this.getViewBounds( distance, _minTarget, _maxTarget );
  16508. return target.subVectors( _maxTarget, _minTarget );
  16509. }
  16510. /**
  16511. * Sets an offset in a larger frustum. This is useful for multi-window or
  16512. * multi-monitor/multi-machine setups.
  16513. *
  16514. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16515. * the monitors are in grid like this
  16516. *```
  16517. * +---+---+---+
  16518. * | A | B | C |
  16519. * +---+---+---+
  16520. * | D | E | F |
  16521. * +---+---+---+
  16522. *```
  16523. * then for each monitor you would call it like this:
  16524. *```js
  16525. * const w = 1920;
  16526. * const h = 1080;
  16527. * const fullWidth = w * 3;
  16528. * const fullHeight = h * 2;
  16529. *
  16530. * // --A--
  16531. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16532. * // --B--
  16533. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16534. * // --C--
  16535. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16536. * // --D--
  16537. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16538. * // --E--
  16539. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16540. * // --F--
  16541. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16542. * ```
  16543. *
  16544. * Note there is no reason monitors have to be the same size or in a grid.
  16545. *
  16546. * @param {number} fullWidth - The full width of multiview setup.
  16547. * @param {number} fullHeight - The full height of multiview setup.
  16548. * @param {number} x - The horizontal offset of the subcamera.
  16549. * @param {number} y - The vertical offset of the subcamera.
  16550. * @param {number} width - The width of subcamera.
  16551. * @param {number} height - The height of subcamera.
  16552. */
  16553. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16554. this.aspect = fullWidth / fullHeight;
  16555. if ( this.view === null ) {
  16556. this.view = {
  16557. enabled: true,
  16558. fullWidth: 1,
  16559. fullHeight: 1,
  16560. offsetX: 0,
  16561. offsetY: 0,
  16562. width: 1,
  16563. height: 1
  16564. };
  16565. }
  16566. this.view.enabled = true;
  16567. this.view.fullWidth = fullWidth;
  16568. this.view.fullHeight = fullHeight;
  16569. this.view.offsetX = x;
  16570. this.view.offsetY = y;
  16571. this.view.width = width;
  16572. this.view.height = height;
  16573. this.updateProjectionMatrix();
  16574. }
  16575. /**
  16576. * Removes the view offset from the projection matrix.
  16577. */
  16578. clearViewOffset() {
  16579. if ( this.view !== null ) {
  16580. this.view.enabled = false;
  16581. }
  16582. this.updateProjectionMatrix();
  16583. }
  16584. /**
  16585. * Updates the camera's projection matrix. Must be called after any change of
  16586. * camera properties.
  16587. */
  16588. updateProjectionMatrix() {
  16589. const near = this.near;
  16590. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16591. let height = 2 * top;
  16592. let width = this.aspect * height;
  16593. let left = -0.5 * width;
  16594. const view = this.view;
  16595. if ( this.view !== null && this.view.enabled ) {
  16596. const fullWidth = view.fullWidth,
  16597. fullHeight = view.fullHeight;
  16598. left += view.offsetX * width / fullWidth;
  16599. top -= view.offsetY * height / fullHeight;
  16600. width *= view.width / fullWidth;
  16601. height *= view.height / fullHeight;
  16602. }
  16603. const skew = this.filmOffset;
  16604. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16605. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16606. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16607. }
  16608. toJSON( meta ) {
  16609. const data = super.toJSON( meta );
  16610. data.object.fov = this.fov;
  16611. data.object.zoom = this.zoom;
  16612. data.object.near = this.near;
  16613. data.object.far = this.far;
  16614. data.object.focus = this.focus;
  16615. data.object.aspect = this.aspect;
  16616. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16617. data.object.filmGauge = this.filmGauge;
  16618. data.object.filmOffset = this.filmOffset;
  16619. return data;
  16620. }
  16621. }
  16622. const fov = -90; // negative fov is not an error
  16623. const aspect = 1;
  16624. /**
  16625. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16626. * cube render target. The render target can then be used as an environment map for rendering
  16627. * realtime reflections in your scene.
  16628. *
  16629. * ```js
  16630. * // Create cube render target
  16631. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16632. *
  16633. * // Create cube camera
  16634. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16635. * scene.add( cubeCamera );
  16636. *
  16637. * // Create car
  16638. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16639. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16640. * scene.add( car );
  16641. *
  16642. * // Update the render target cube
  16643. * car.visible = false;
  16644. * cubeCamera.position.copy( car.position );
  16645. * cubeCamera.update( renderer, scene );
  16646. *
  16647. * // Render the scene
  16648. * car.visible = true;
  16649. * renderer.render( scene, camera );
  16650. * ```
  16651. *
  16652. * @augments Object3D
  16653. */
  16654. class CubeCamera extends Object3D {
  16655. /**
  16656. * Constructs a new cube camera.
  16657. *
  16658. * @param {number} near - The camera's near plane.
  16659. * @param {number} far - The camera's far plane.
  16660. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16661. */
  16662. constructor( near, far, renderTarget ) {
  16663. super();
  16664. this.type = 'CubeCamera';
  16665. /**
  16666. * A reference to the cube render target.
  16667. *
  16668. * @type {WebGLCubeRenderTarget}
  16669. */
  16670. this.renderTarget = renderTarget;
  16671. /**
  16672. * The current active coordinate system.
  16673. *
  16674. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16675. * @default null
  16676. */
  16677. this.coordinateSystem = null;
  16678. /**
  16679. * The current active mipmap level
  16680. *
  16681. * @type {number}
  16682. * @default 0
  16683. */
  16684. this.activeMipmapLevel = 0;
  16685. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16686. cameraPX.layers = this.layers;
  16687. this.add( cameraPX );
  16688. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16689. cameraNX.layers = this.layers;
  16690. this.add( cameraNX );
  16691. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16692. cameraPY.layers = this.layers;
  16693. this.add( cameraPY );
  16694. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16695. cameraNY.layers = this.layers;
  16696. this.add( cameraNY );
  16697. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16698. cameraPZ.layers = this.layers;
  16699. this.add( cameraPZ );
  16700. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16701. cameraNZ.layers = this.layers;
  16702. this.add( cameraNZ );
  16703. }
  16704. /**
  16705. * Must be called when the coordinate system of the cube camera is changed.
  16706. */
  16707. updateCoordinateSystem() {
  16708. const coordinateSystem = this.coordinateSystem;
  16709. const cameras = this.children.concat();
  16710. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16711. for ( const camera of cameras ) this.remove( camera );
  16712. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16713. cameraPX.up.set( 0, 1, 0 );
  16714. cameraPX.lookAt( 1, 0, 0 );
  16715. cameraNX.up.set( 0, 1, 0 );
  16716. cameraNX.lookAt( -1, 0, 0 );
  16717. cameraPY.up.set( 0, 0, -1 );
  16718. cameraPY.lookAt( 0, 1, 0 );
  16719. cameraNY.up.set( 0, 0, 1 );
  16720. cameraNY.lookAt( 0, -1, 0 );
  16721. cameraPZ.up.set( 0, 1, 0 );
  16722. cameraPZ.lookAt( 0, 0, 1 );
  16723. cameraNZ.up.set( 0, 1, 0 );
  16724. cameraNZ.lookAt( 0, 0, -1 );
  16725. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16726. cameraPX.up.set( 0, -1, 0 );
  16727. cameraPX.lookAt( -1, 0, 0 );
  16728. cameraNX.up.set( 0, -1, 0 );
  16729. cameraNX.lookAt( 1, 0, 0 );
  16730. cameraPY.up.set( 0, 0, 1 );
  16731. cameraPY.lookAt( 0, 1, 0 );
  16732. cameraNY.up.set( 0, 0, -1 );
  16733. cameraNY.lookAt( 0, -1, 0 );
  16734. cameraPZ.up.set( 0, -1, 0 );
  16735. cameraPZ.lookAt( 0, 0, 1 );
  16736. cameraNZ.up.set( 0, -1, 0 );
  16737. cameraNZ.lookAt( 0, 0, -1 );
  16738. } else {
  16739. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16740. }
  16741. for ( const camera of cameras ) {
  16742. this.add( camera );
  16743. camera.updateMatrixWorld();
  16744. }
  16745. }
  16746. /**
  16747. * Calling this method will render the given scene with the given renderer
  16748. * into the cube render target of the camera.
  16749. *
  16750. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16751. * @param {Scene} scene - The scene to render.
  16752. */
  16753. update( renderer, scene ) {
  16754. if ( this.parent === null ) this.updateMatrixWorld();
  16755. const { renderTarget, activeMipmapLevel } = this;
  16756. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16757. this.coordinateSystem = renderer.coordinateSystem;
  16758. this.updateCoordinateSystem();
  16759. }
  16760. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16761. const currentRenderTarget = renderer.getRenderTarget();
  16762. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16763. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16764. const currentXrEnabled = renderer.xr.enabled;
  16765. renderer.xr.enabled = false;
  16766. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16767. renderTarget.texture.generateMipmaps = false;
  16768. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  16769. const reversedDepthBuffer = !! ( renderer.isWebGLRenderer && renderer.state.buffers.depth.getReversed() );
  16770. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16771. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16772. renderer.render( scene, cameraPX );
  16773. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16774. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16775. renderer.render( scene, cameraNX );
  16776. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16777. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16778. renderer.render( scene, cameraPY );
  16779. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16780. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16781. renderer.render( scene, cameraNY );
  16782. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16783. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16784. renderer.render( scene, cameraPZ );
  16785. // mipmaps are generated during the last call of render()
  16786. // at this point, all sides of the cube render target are defined
  16787. renderTarget.texture.generateMipmaps = generateMipmaps;
  16788. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16789. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  16790. renderer.render( scene, cameraNZ );
  16791. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16792. renderer.xr.enabled = currentXrEnabled;
  16793. renderTarget.texture.needsPMREMUpdate = true;
  16794. }
  16795. }
  16796. /**
  16797. * Creates a cube texture made up of six images.
  16798. *
  16799. * ```js
  16800. * const loader = new THREE.CubeTextureLoader();
  16801. * loader.setPath( 'textures/cube/pisa/' );
  16802. *
  16803. * const textureCube = loader.load( [
  16804. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16805. * ] );
  16806. *
  16807. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16808. * ```
  16809. *
  16810. * @augments Texture
  16811. */
  16812. class CubeTexture extends Texture {
  16813. /**
  16814. * Constructs a new cube texture.
  16815. *
  16816. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16817. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16818. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16819. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16820. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16821. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16822. * @param {number} [format=RGBAFormat] - The texture format.
  16823. * @param {number} [type=UnsignedByteType] - The texture type.
  16824. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16825. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16826. */
  16827. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16828. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16829. /**
  16830. * This flag can be used for type testing.
  16831. *
  16832. * @type {boolean}
  16833. * @readonly
  16834. * @default true
  16835. */
  16836. this.isCubeTexture = true;
  16837. /**
  16838. * If set to `true`, the texture is flipped along the vertical axis when
  16839. * uploaded to the GPU.
  16840. *
  16841. * Overwritten and set to `false` by default.
  16842. *
  16843. * @type {boolean}
  16844. * @default false
  16845. */
  16846. this.flipY = false;
  16847. }
  16848. /**
  16849. * Alias for {@link CubeTexture#image}.
  16850. *
  16851. * @type {Array<Image>}
  16852. */
  16853. get images() {
  16854. return this.image;
  16855. }
  16856. set images( value ) {
  16857. this.image = value;
  16858. }
  16859. }
  16860. /**
  16861. * A cube render target used in context of {@link WebGLRenderer}.
  16862. *
  16863. * @augments WebGLRenderTarget
  16864. */
  16865. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16866. /**
  16867. * Constructs a new cube render target.
  16868. *
  16869. * @param {number} [size=1] - The size of the render target.
  16870. * @param {RenderTarget~Options} [options] - The configuration object.
  16871. */
  16872. constructor( size = 1, options = {} ) {
  16873. super( size, size, options );
  16874. /**
  16875. * This flag can be used for type testing.
  16876. *
  16877. * @type {boolean}
  16878. * @readonly
  16879. * @default true
  16880. */
  16881. this.isWebGLCubeRenderTarget = true;
  16882. const image = { width: size, height: size, depth: 1 };
  16883. const images = [ image, image, image, image, image, image ];
  16884. /**
  16885. * Overwritten with a different texture type.
  16886. *
  16887. * @type {DataArrayTexture}
  16888. */
  16889. this.texture = new CubeTexture( images );
  16890. this._setTextureOptions( options );
  16891. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16892. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16893. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16894. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16895. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16896. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16897. this.texture.isRenderTargetTexture = true;
  16898. }
  16899. /**
  16900. * Converts the given equirectangular texture to a cube map.
  16901. *
  16902. * @param {WebGLRenderer} renderer - The renderer.
  16903. * @param {Texture} texture - The equirectangular texture.
  16904. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16905. */
  16906. fromEquirectangularTexture( renderer, texture ) {
  16907. this.texture.type = texture.type;
  16908. this.texture.colorSpace = texture.colorSpace;
  16909. this.texture.generateMipmaps = texture.generateMipmaps;
  16910. this.texture.minFilter = texture.minFilter;
  16911. this.texture.magFilter = texture.magFilter;
  16912. const shader = {
  16913. uniforms: {
  16914. tEquirect: { value: null },
  16915. },
  16916. vertexShader: /* glsl */`
  16917. varying vec3 vWorldDirection;
  16918. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16919. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16920. }
  16921. void main() {
  16922. vWorldDirection = transformDirection( position, modelMatrix );
  16923. #include <begin_vertex>
  16924. #include <project_vertex>
  16925. }
  16926. `,
  16927. fragmentShader: /* glsl */`
  16928. uniform sampler2D tEquirect;
  16929. varying vec3 vWorldDirection;
  16930. #include <common>
  16931. void main() {
  16932. vec3 direction = normalize( vWorldDirection );
  16933. vec2 sampleUV = equirectUv( direction );
  16934. gl_FragColor = texture2D( tEquirect, sampleUV );
  16935. }
  16936. `
  16937. };
  16938. const geometry = new BoxGeometry( 5, 5, 5 );
  16939. const material = new ShaderMaterial( {
  16940. name: 'CubemapFromEquirect',
  16941. uniforms: cloneUniforms( shader.uniforms ),
  16942. vertexShader: shader.vertexShader,
  16943. fragmentShader: shader.fragmentShader,
  16944. side: BackSide,
  16945. blending: NoBlending
  16946. } );
  16947. material.uniforms.tEquirect.value = texture;
  16948. const mesh = new Mesh( geometry, material );
  16949. const currentMinFilter = texture.minFilter;
  16950. // Avoid blurred poles
  16951. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16952. const camera = new CubeCamera( 1, 10, this );
  16953. camera.update( renderer, mesh );
  16954. texture.minFilter = currentMinFilter;
  16955. mesh.geometry.dispose();
  16956. mesh.material.dispose();
  16957. return this;
  16958. }
  16959. /**
  16960. * Clears this cube render target.
  16961. *
  16962. * @param {WebGLRenderer} renderer - The renderer.
  16963. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16964. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16965. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16966. */
  16967. clear( renderer, color = true, depth = true, stencil = true ) {
  16968. const currentRenderTarget = renderer.getRenderTarget();
  16969. for ( let i = 0; i < 6; i ++ ) {
  16970. renderer.setRenderTarget( this, i );
  16971. renderer.clear( color, depth, stencil );
  16972. }
  16973. renderer.setRenderTarget( currentRenderTarget );
  16974. }
  16975. }
  16976. /**
  16977. * This is almost identical to an {@link Object3D}. Its purpose is to
  16978. * make working with groups of objects syntactically clearer.
  16979. *
  16980. * ```js
  16981. * // Create a group and add the two cubes.
  16982. * // These cubes can now be rotated / scaled etc as a group.
  16983. * const group = new THREE.Group();
  16984. *
  16985. * group.add( meshA );
  16986. * group.add( meshB );
  16987. *
  16988. * scene.add( group );
  16989. * ```
  16990. *
  16991. * @augments Object3D
  16992. */
  16993. class Group extends Object3D {
  16994. constructor() {
  16995. super();
  16996. /**
  16997. * This flag can be used for type testing.
  16998. *
  16999. * @type {boolean}
  17000. * @readonly
  17001. * @default true
  17002. */
  17003. this.isGroup = true;
  17004. this.type = 'Group';
  17005. }
  17006. }
  17007. const _moveEvent = { type: 'move' };
  17008. /**
  17009. * Class for representing a XR controller with its
  17010. * different coordinate systems.
  17011. *
  17012. * @private
  17013. */
  17014. class WebXRController {
  17015. /**
  17016. * Constructs a new XR controller.
  17017. */
  17018. constructor() {
  17019. /**
  17020. * A group representing the target ray space
  17021. * of the XR controller.
  17022. *
  17023. * @private
  17024. * @type {?Group}
  17025. * @default null
  17026. */
  17027. this._targetRay = null;
  17028. /**
  17029. * A group representing the grip space
  17030. * of the XR controller.
  17031. *
  17032. * @private
  17033. * @type {?Group}
  17034. * @default null
  17035. */
  17036. this._grip = null;
  17037. /**
  17038. * A group representing the hand space
  17039. * of the XR controller.
  17040. *
  17041. * @private
  17042. * @type {?Group}
  17043. * @default null
  17044. */
  17045. this._hand = null;
  17046. }
  17047. /**
  17048. * Returns a group representing the hand space of the XR controller.
  17049. *
  17050. * @return {Group} A group representing the hand space of the XR controller.
  17051. */
  17052. getHandSpace() {
  17053. if ( this._hand === null ) {
  17054. this._hand = new Group();
  17055. this._hand.matrixAutoUpdate = false;
  17056. this._hand.visible = false;
  17057. this._hand.joints = {};
  17058. this._hand.inputState = { pinching: false };
  17059. }
  17060. return this._hand;
  17061. }
  17062. /**
  17063. * Returns a group representing the target ray space of the XR controller.
  17064. *
  17065. * @return {Group} A group representing the target ray space of the XR controller.
  17066. */
  17067. getTargetRaySpace() {
  17068. if ( this._targetRay === null ) {
  17069. this._targetRay = new Group();
  17070. this._targetRay.matrixAutoUpdate = false;
  17071. this._targetRay.visible = false;
  17072. this._targetRay.hasLinearVelocity = false;
  17073. this._targetRay.linearVelocity = new Vector3();
  17074. this._targetRay.hasAngularVelocity = false;
  17075. this._targetRay.angularVelocity = new Vector3();
  17076. }
  17077. return this._targetRay;
  17078. }
  17079. /**
  17080. * Returns a group representing the grip space of the XR controller.
  17081. *
  17082. * @return {Group} A group representing the grip space of the XR controller.
  17083. */
  17084. getGripSpace() {
  17085. if ( this._grip === null ) {
  17086. this._grip = new Group();
  17087. this._grip.matrixAutoUpdate = false;
  17088. this._grip.visible = false;
  17089. this._grip.hasLinearVelocity = false;
  17090. this._grip.linearVelocity = new Vector3();
  17091. this._grip.hasAngularVelocity = false;
  17092. this._grip.angularVelocity = new Vector3();
  17093. }
  17094. return this._grip;
  17095. }
  17096. /**
  17097. * Dispatches the given event to the groups representing
  17098. * the different coordinate spaces of the XR controller.
  17099. *
  17100. * @param {Object} event - The event to dispatch.
  17101. * @return {WebXRController} A reference to this instance.
  17102. */
  17103. dispatchEvent( event ) {
  17104. if ( this._targetRay !== null ) {
  17105. this._targetRay.dispatchEvent( event );
  17106. }
  17107. if ( this._grip !== null ) {
  17108. this._grip.dispatchEvent( event );
  17109. }
  17110. if ( this._hand !== null ) {
  17111. this._hand.dispatchEvent( event );
  17112. }
  17113. return this;
  17114. }
  17115. /**
  17116. * Connects the controller with the given XR input source.
  17117. *
  17118. * @param {XRInputSource} inputSource - The input source.
  17119. * @return {WebXRController} A reference to this instance.
  17120. */
  17121. connect( inputSource ) {
  17122. if ( inputSource && inputSource.hand ) {
  17123. const hand = this._hand;
  17124. if ( hand ) {
  17125. for ( const inputjoint of inputSource.hand.values() ) {
  17126. // Initialize hand with joints when connected
  17127. this._getHandJoint( hand, inputjoint );
  17128. }
  17129. }
  17130. }
  17131. this.dispatchEvent( { type: 'connected', data: inputSource } );
  17132. return this;
  17133. }
  17134. /**
  17135. * Disconnects the controller from the given XR input source.
  17136. *
  17137. * @param {XRInputSource} inputSource - The input source.
  17138. * @return {WebXRController} A reference to this instance.
  17139. */
  17140. disconnect( inputSource ) {
  17141. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  17142. if ( this._targetRay !== null ) {
  17143. this._targetRay.visible = false;
  17144. }
  17145. if ( this._grip !== null ) {
  17146. this._grip.visible = false;
  17147. }
  17148. if ( this._hand !== null ) {
  17149. this._hand.visible = false;
  17150. }
  17151. return this;
  17152. }
  17153. /**
  17154. * Updates the controller with the given input source, XR frame and reference space.
  17155. * This updates the transformations of the groups that represent the different
  17156. * coordinate systems of the controller.
  17157. *
  17158. * @param {XRInputSource} inputSource - The input source.
  17159. * @param {XRFrame} frame - The XR frame.
  17160. * @param {XRReferenceSpace} referenceSpace - The reference space.
  17161. * @return {WebXRController} A reference to this instance.
  17162. */
  17163. update( inputSource, frame, referenceSpace ) {
  17164. let inputPose = null;
  17165. let gripPose = null;
  17166. let handPose = null;
  17167. const targetRay = this._targetRay;
  17168. const grip = this._grip;
  17169. const hand = this._hand;
  17170. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  17171. if ( hand && inputSource.hand ) {
  17172. handPose = true;
  17173. for ( const inputjoint of inputSource.hand.values() ) {
  17174. // Update the joints groups with the XRJoint poses
  17175. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  17176. // The transform of this joint will be updated with the joint pose on each frame
  17177. const joint = this._getHandJoint( hand, inputjoint );
  17178. if ( jointPose !== null ) {
  17179. joint.matrix.fromArray( jointPose.transform.matrix );
  17180. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  17181. joint.matrixWorldNeedsUpdate = true;
  17182. joint.jointRadius = jointPose.radius;
  17183. }
  17184. joint.visible = jointPose !== null;
  17185. }
  17186. // Custom events
  17187. // Check pinchz
  17188. const indexTip = hand.joints[ 'index-finger-tip' ];
  17189. const thumbTip = hand.joints[ 'thumb-tip' ];
  17190. const distance = indexTip.position.distanceTo( thumbTip.position );
  17191. const distanceToPinch = 0.02;
  17192. const threshold = 0.005;
  17193. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  17194. hand.inputState.pinching = false;
  17195. this.dispatchEvent( {
  17196. type: 'pinchend',
  17197. handedness: inputSource.handedness,
  17198. target: this
  17199. } );
  17200. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  17201. hand.inputState.pinching = true;
  17202. this.dispatchEvent( {
  17203. type: 'pinchstart',
  17204. handedness: inputSource.handedness,
  17205. target: this
  17206. } );
  17207. }
  17208. } else {
  17209. if ( grip !== null && inputSource.gripSpace ) {
  17210. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  17211. if ( gripPose !== null ) {
  17212. grip.matrix.fromArray( gripPose.transform.matrix );
  17213. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  17214. grip.matrixWorldNeedsUpdate = true;
  17215. if ( gripPose.linearVelocity ) {
  17216. grip.hasLinearVelocity = true;
  17217. grip.linearVelocity.copy( gripPose.linearVelocity );
  17218. } else {
  17219. grip.hasLinearVelocity = false;
  17220. }
  17221. if ( gripPose.angularVelocity ) {
  17222. grip.hasAngularVelocity = true;
  17223. grip.angularVelocity.copy( gripPose.angularVelocity );
  17224. } else {
  17225. grip.hasAngularVelocity = false;
  17226. }
  17227. }
  17228. }
  17229. }
  17230. if ( targetRay !== null ) {
  17231. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17232. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17233. if ( inputPose === null && gripPose !== null ) {
  17234. inputPose = gripPose;
  17235. }
  17236. if ( inputPose !== null ) {
  17237. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17238. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17239. targetRay.matrixWorldNeedsUpdate = true;
  17240. if ( inputPose.linearVelocity ) {
  17241. targetRay.hasLinearVelocity = true;
  17242. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17243. } else {
  17244. targetRay.hasLinearVelocity = false;
  17245. }
  17246. if ( inputPose.angularVelocity ) {
  17247. targetRay.hasAngularVelocity = true;
  17248. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17249. } else {
  17250. targetRay.hasAngularVelocity = false;
  17251. }
  17252. this.dispatchEvent( _moveEvent );
  17253. }
  17254. }
  17255. }
  17256. if ( targetRay !== null ) {
  17257. targetRay.visible = ( inputPose !== null );
  17258. }
  17259. if ( grip !== null ) {
  17260. grip.visible = ( gripPose !== null );
  17261. }
  17262. if ( hand !== null ) {
  17263. hand.visible = ( handPose !== null );
  17264. }
  17265. return this;
  17266. }
  17267. /**
  17268. * Returns a group representing the hand joint for the given input joint.
  17269. *
  17270. * @private
  17271. * @param {Group} hand - The group representing the hand space.
  17272. * @param {XRJointSpace} inputjoint - The hand joint data.
  17273. * @return {Group} A group representing the hand joint for the given input joint.
  17274. */
  17275. _getHandJoint( hand, inputjoint ) {
  17276. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17277. const joint = new Group();
  17278. joint.matrixAutoUpdate = false;
  17279. joint.visible = false;
  17280. hand.joints[ inputjoint.jointName ] = joint;
  17281. hand.add( joint );
  17282. }
  17283. return hand.joints[ inputjoint.jointName ];
  17284. }
  17285. }
  17286. /**
  17287. * This class can be used to define an exponential squared fog,
  17288. * which gives a clear view near the camera and a faster than exponentially
  17289. * densening fog farther from the camera.
  17290. *
  17291. * ```js
  17292. * const scene = new THREE.Scene();
  17293. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17294. * ```
  17295. */
  17296. class FogExp2 {
  17297. /**
  17298. * Constructs a new fog.
  17299. *
  17300. * @param {number|Color} color - The fog's color.
  17301. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17302. */
  17303. constructor( color, density = 0.00025 ) {
  17304. /**
  17305. * This flag can be used for type testing.
  17306. *
  17307. * @type {boolean}
  17308. * @readonly
  17309. * @default true
  17310. */
  17311. this.isFogExp2 = true;
  17312. /**
  17313. * The name of the fog.
  17314. *
  17315. * @type {string}
  17316. */
  17317. this.name = '';
  17318. /**
  17319. * The fog's color.
  17320. *
  17321. * @type {Color}
  17322. */
  17323. this.color = new Color( color );
  17324. /**
  17325. * Defines how fast the fog will grow dense.
  17326. *
  17327. * @type {number}
  17328. * @default 0.00025
  17329. */
  17330. this.density = density;
  17331. }
  17332. /**
  17333. * Returns a new fog with copied values from this instance.
  17334. *
  17335. * @return {FogExp2} A clone of this instance.
  17336. */
  17337. clone() {
  17338. return new FogExp2( this.color, this.density );
  17339. }
  17340. /**
  17341. * Serializes the fog into JSON.
  17342. *
  17343. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17344. * @return {Object} A JSON object representing the serialized fog
  17345. */
  17346. toJSON( /* meta */ ) {
  17347. return {
  17348. type: 'FogExp2',
  17349. name: this.name,
  17350. color: this.color.getHex(),
  17351. density: this.density
  17352. };
  17353. }
  17354. }
  17355. /**
  17356. * This class can be used to define a linear fog that grows linearly denser
  17357. * with the distance.
  17358. *
  17359. * ```js
  17360. * const scene = new THREE.Scene();
  17361. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17362. * ```
  17363. */
  17364. class Fog {
  17365. /**
  17366. * Constructs a new fog.
  17367. *
  17368. * @param {number|Color} color - The fog's color.
  17369. * @param {number} [near=1] - The minimum distance to start applying fog.
  17370. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17371. */
  17372. constructor( color, near = 1, far = 1000 ) {
  17373. /**
  17374. * This flag can be used for type testing.
  17375. *
  17376. * @type {boolean}
  17377. * @readonly
  17378. * @default true
  17379. */
  17380. this.isFog = true;
  17381. /**
  17382. * The name of the fog.
  17383. *
  17384. * @type {string}
  17385. */
  17386. this.name = '';
  17387. /**
  17388. * The fog's color.
  17389. *
  17390. * @type {Color}
  17391. */
  17392. this.color = new Color( color );
  17393. /**
  17394. * The minimum distance to start applying fog. Objects that are less than
  17395. * `near` units from the active camera won't be affected by fog.
  17396. *
  17397. * @type {number}
  17398. * @default 1
  17399. */
  17400. this.near = near;
  17401. /**
  17402. * The maximum distance at which fog stops being calculated and applied.
  17403. * Objects that are more than `far` units away from the active camera won't
  17404. * be affected by fog.
  17405. *
  17406. * @type {number}
  17407. * @default 1000
  17408. */
  17409. this.far = far;
  17410. }
  17411. /**
  17412. * Returns a new fog with copied values from this instance.
  17413. *
  17414. * @return {Fog} A clone of this instance.
  17415. */
  17416. clone() {
  17417. return new Fog( this.color, this.near, this.far );
  17418. }
  17419. /**
  17420. * Serializes the fog into JSON.
  17421. *
  17422. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17423. * @return {Object} A JSON object representing the serialized fog
  17424. */
  17425. toJSON( /* meta */ ) {
  17426. return {
  17427. type: 'Fog',
  17428. name: this.name,
  17429. color: this.color.getHex(),
  17430. near: this.near,
  17431. far: this.far
  17432. };
  17433. }
  17434. }
  17435. /**
  17436. * Scenes allow you to set up what is to be rendered and where by three.js.
  17437. * This is where you place 3D objects like meshes, lines or lights.
  17438. *
  17439. * @augments Object3D
  17440. */
  17441. class Scene extends Object3D {
  17442. /**
  17443. * Constructs a new scene.
  17444. */
  17445. constructor() {
  17446. super();
  17447. /**
  17448. * This flag can be used for type testing.
  17449. *
  17450. * @type {boolean}
  17451. * @readonly
  17452. * @default true
  17453. */
  17454. this.isScene = true;
  17455. this.type = 'Scene';
  17456. /**
  17457. * Defines the background of the scene. Valid inputs are:
  17458. *
  17459. * - A color for defining a uniform colored background.
  17460. * - A texture for defining a (flat) textured background.
  17461. * - Cube textures or equirectangular textures for defining a skybox.
  17462. *
  17463. * @type {?(Color|Texture)}
  17464. * @default null
  17465. */
  17466. this.background = null;
  17467. /**
  17468. * Sets the environment map for all physical materials in the scene. However,
  17469. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17470. * material property.
  17471. *
  17472. * @type {?Texture}
  17473. * @default null
  17474. */
  17475. this.environment = null;
  17476. /**
  17477. * A fog instance defining the type of fog that affects everything
  17478. * rendered in the scene.
  17479. *
  17480. * @type {?(Fog|FogExp2)}
  17481. * @default null
  17482. */
  17483. this.fog = null;
  17484. /**
  17485. * Sets the blurriness of the background. Only influences environment maps
  17486. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17487. * and `1`.
  17488. *
  17489. * @type {number}
  17490. * @default 0
  17491. */
  17492. this.backgroundBlurriness = 0;
  17493. /**
  17494. * Attenuates the color of the background. Only applies to background textures.
  17495. *
  17496. * @type {number}
  17497. * @default 1
  17498. */
  17499. this.backgroundIntensity = 1;
  17500. /**
  17501. * The rotation of the background in radians. Only influences environment maps
  17502. * assigned to {@link Scene#background}.
  17503. *
  17504. * @type {Euler}
  17505. * @default (0,0,0)
  17506. */
  17507. this.backgroundRotation = new Euler();
  17508. /**
  17509. * Attenuates the color of the environment. Only influences environment maps
  17510. * assigned to {@link Scene#environment}.
  17511. *
  17512. * @type {number}
  17513. * @default 1
  17514. */
  17515. this.environmentIntensity = 1;
  17516. /**
  17517. * The rotation of the environment map in radians. Only influences physical materials
  17518. * in the scene when {@link Scene#environment} is used.
  17519. *
  17520. * @type {Euler}
  17521. * @default (0,0,0)
  17522. */
  17523. this.environmentRotation = new Euler();
  17524. /**
  17525. * Forces everything in the scene to be rendered with the defined material. It is possible
  17526. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17527. *
  17528. * @type {?Material}
  17529. * @default null
  17530. */
  17531. this.overrideMaterial = null;
  17532. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17533. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17534. }
  17535. }
  17536. copy( source, recursive ) {
  17537. super.copy( source, recursive );
  17538. if ( source.background !== null ) this.background = source.background.clone();
  17539. if ( source.environment !== null ) this.environment = source.environment.clone();
  17540. if ( source.fog !== null ) this.fog = source.fog.clone();
  17541. this.backgroundBlurriness = source.backgroundBlurriness;
  17542. this.backgroundIntensity = source.backgroundIntensity;
  17543. this.backgroundRotation.copy( source.backgroundRotation );
  17544. this.environmentIntensity = source.environmentIntensity;
  17545. this.environmentRotation.copy( source.environmentRotation );
  17546. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17547. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17548. return this;
  17549. }
  17550. toJSON( meta ) {
  17551. const data = super.toJSON( meta );
  17552. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17553. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17554. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17555. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17556. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17557. data.object.environmentRotation = this.environmentRotation.toArray();
  17558. return data;
  17559. }
  17560. }
  17561. /**
  17562. * "Interleaved" means that multiple attributes, possibly of different types,
  17563. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17564. *
  17565. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17566. */
  17567. class InterleavedBuffer {
  17568. /**
  17569. * Constructs a new interleaved buffer.
  17570. *
  17571. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17572. * @param {number} stride - The number of typed-array elements per vertex.
  17573. */
  17574. constructor( array, stride ) {
  17575. /**
  17576. * This flag can be used for type testing.
  17577. *
  17578. * @type {boolean}
  17579. * @readonly
  17580. * @default true
  17581. */
  17582. this.isInterleavedBuffer = true;
  17583. /**
  17584. * A typed array with a shared buffer storing attribute data.
  17585. *
  17586. * @type {TypedArray}
  17587. */
  17588. this.array = array;
  17589. /**
  17590. * The number of typed-array elements per vertex.
  17591. *
  17592. * @type {number}
  17593. */
  17594. this.stride = stride;
  17595. /**
  17596. * The total number of elements in the array
  17597. *
  17598. * @type {number}
  17599. * @readonly
  17600. */
  17601. this.count = array !== undefined ? array.length / stride : 0;
  17602. /**
  17603. * Defines the intended usage pattern of the data store for optimization purposes.
  17604. *
  17605. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17606. * instantiate a new one and set the desired usage before the next render.
  17607. *
  17608. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17609. * @default StaticDrawUsage
  17610. */
  17611. this.usage = StaticDrawUsage;
  17612. /**
  17613. * This can be used to only update some components of stored vectors (for example, just the
  17614. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17615. *
  17616. * @type {Array<Object>}
  17617. */
  17618. this.updateRanges = [];
  17619. /**
  17620. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17621. *
  17622. * @type {number}
  17623. */
  17624. this.version = 0;
  17625. /**
  17626. * The UUID of the interleaved buffer.
  17627. *
  17628. * @type {string}
  17629. * @readonly
  17630. */
  17631. this.uuid = generateUUID();
  17632. }
  17633. /**
  17634. * A callback function that is executed after the renderer has transferred the attribute array
  17635. * data to the GPU.
  17636. */
  17637. onUploadCallback() {}
  17638. /**
  17639. * Flag to indicate that this attribute has changed and should be re-sent to
  17640. * the GPU. Set this to `true` when you modify the value of the array.
  17641. *
  17642. * @type {number}
  17643. * @default false
  17644. * @param {boolean} value
  17645. */
  17646. set needsUpdate( value ) {
  17647. if ( value === true ) this.version ++;
  17648. }
  17649. /**
  17650. * Sets the usage of this interleaved buffer.
  17651. *
  17652. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17653. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17654. */
  17655. setUsage( value ) {
  17656. this.usage = value;
  17657. return this;
  17658. }
  17659. /**
  17660. * Adds a range of data in the data array to be updated on the GPU.
  17661. *
  17662. * @param {number} start - Position at which to start update.
  17663. * @param {number} count - The number of components to update.
  17664. */
  17665. addUpdateRange( start, count ) {
  17666. this.updateRanges.push( { start, count } );
  17667. }
  17668. /**
  17669. * Clears the update ranges.
  17670. */
  17671. clearUpdateRanges() {
  17672. this.updateRanges.length = 0;
  17673. }
  17674. /**
  17675. * Copies the values of the given interleaved buffer to this instance.
  17676. *
  17677. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17678. * @return {InterleavedBuffer} A reference to this instance.
  17679. */
  17680. copy( source ) {
  17681. this.array = new source.array.constructor( source.array );
  17682. this.count = source.count;
  17683. this.stride = source.stride;
  17684. this.usage = source.usage;
  17685. return this;
  17686. }
  17687. /**
  17688. * Copies a vector from the given interleaved buffer to this one. The start
  17689. * and destination position in the attribute buffers are represented by the
  17690. * given indices.
  17691. *
  17692. * @param {number} index1 - The destination index into this interleaved buffer.
  17693. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17694. * @param {number} index2 - The source index into the given interleaved buffer.
  17695. * @return {InterleavedBuffer} A reference to this instance.
  17696. */
  17697. copyAt( index1, interleavedBuffer, index2 ) {
  17698. index1 *= this.stride;
  17699. index2 *= interleavedBuffer.stride;
  17700. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17701. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17702. }
  17703. return this;
  17704. }
  17705. /**
  17706. * Sets the given array data in the interleaved buffer.
  17707. *
  17708. * @param {(TypedArray|Array)} value - The array data to set.
  17709. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17710. * @return {InterleavedBuffer} A reference to this instance.
  17711. */
  17712. set( value, offset = 0 ) {
  17713. this.array.set( value, offset );
  17714. return this;
  17715. }
  17716. /**
  17717. * Returns a new interleaved buffer with copied values from this instance.
  17718. *
  17719. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17720. * @return {InterleavedBuffer} A clone of this instance.
  17721. */
  17722. clone( data ) {
  17723. if ( data.arrayBuffers === undefined ) {
  17724. data.arrayBuffers = {};
  17725. }
  17726. if ( this.array.buffer._uuid === undefined ) {
  17727. this.array.buffer._uuid = generateUUID();
  17728. }
  17729. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17730. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17731. }
  17732. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17733. const ib = new this.constructor( array, this.stride );
  17734. ib.setUsage( this.usage );
  17735. return ib;
  17736. }
  17737. /**
  17738. * Sets the given callback function that is executed after the Renderer has transferred
  17739. * the array data to the GPU. Can be used to perform clean-up operations after
  17740. * the upload when data are not needed anymore on the CPU side.
  17741. *
  17742. * @param {Function} callback - The `onUpload()` callback.
  17743. * @return {InterleavedBuffer} A reference to this instance.
  17744. */
  17745. onUpload( callback ) {
  17746. this.onUploadCallback = callback;
  17747. return this;
  17748. }
  17749. /**
  17750. * Serializes the interleaved buffer into JSON.
  17751. *
  17752. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17753. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17754. */
  17755. toJSON( data ) {
  17756. if ( data.arrayBuffers === undefined ) {
  17757. data.arrayBuffers = {};
  17758. }
  17759. // generate UUID for array buffer if necessary
  17760. if ( this.array.buffer._uuid === undefined ) {
  17761. this.array.buffer._uuid = generateUUID();
  17762. }
  17763. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17764. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17765. }
  17766. //
  17767. return {
  17768. uuid: this.uuid,
  17769. buffer: this.array.buffer._uuid,
  17770. type: this.array.constructor.name,
  17771. stride: this.stride
  17772. };
  17773. }
  17774. }
  17775. const _vector$7 = /*@__PURE__*/ new Vector3();
  17776. /**
  17777. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17778. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17779. * different offsets into the buffer.
  17780. */
  17781. class InterleavedBufferAttribute {
  17782. /**
  17783. * Constructs a new interleaved buffer attribute.
  17784. *
  17785. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17786. * @param {number} itemSize - The item size.
  17787. * @param {number} offset - The attribute offset into the buffer.
  17788. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17789. */
  17790. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17791. /**
  17792. * This flag can be used for type testing.
  17793. *
  17794. * @type {boolean}
  17795. * @readonly
  17796. * @default true
  17797. */
  17798. this.isInterleavedBufferAttribute = true;
  17799. /**
  17800. * The name of the buffer attribute.
  17801. *
  17802. * @type {string}
  17803. */
  17804. this.name = '';
  17805. /**
  17806. * The buffer holding the interleaved data.
  17807. *
  17808. * @type {InterleavedBuffer}
  17809. */
  17810. this.data = interleavedBuffer;
  17811. /**
  17812. * The item size, see {@link BufferAttribute#itemSize}.
  17813. *
  17814. * @type {number}
  17815. */
  17816. this.itemSize = itemSize;
  17817. /**
  17818. * The attribute offset into the buffer.
  17819. *
  17820. * @type {number}
  17821. */
  17822. this.offset = offset;
  17823. /**
  17824. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17825. *
  17826. * @type {InterleavedBuffer}
  17827. */
  17828. this.normalized = normalized;
  17829. }
  17830. /**
  17831. * The item count of this buffer attribute.
  17832. *
  17833. * @type {number}
  17834. * @readonly
  17835. */
  17836. get count() {
  17837. return this.data.count;
  17838. }
  17839. /**
  17840. * The array holding the interleaved buffer attribute data.
  17841. *
  17842. * @type {TypedArray}
  17843. */
  17844. get array() {
  17845. return this.data.array;
  17846. }
  17847. /**
  17848. * Flag to indicate that this attribute has changed and should be re-sent to
  17849. * the GPU. Set this to `true` when you modify the value of the array.
  17850. *
  17851. * @type {number}
  17852. * @default false
  17853. * @param {boolean} value
  17854. */
  17855. set needsUpdate( value ) {
  17856. this.data.needsUpdate = value;
  17857. }
  17858. /**
  17859. * Applies the given 4x4 matrix to the given attribute. Only works with
  17860. * item size `3`.
  17861. *
  17862. * @param {Matrix4} m - The matrix to apply.
  17863. * @return {InterleavedBufferAttribute} A reference to this instance.
  17864. */
  17865. applyMatrix4( m ) {
  17866. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17867. _vector$7.fromBufferAttribute( this, i );
  17868. _vector$7.applyMatrix4( m );
  17869. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17870. }
  17871. return this;
  17872. }
  17873. /**
  17874. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17875. * item size `3`.
  17876. *
  17877. * @param {Matrix3} m - The normal matrix to apply.
  17878. * @return {InterleavedBufferAttribute} A reference to this instance.
  17879. */
  17880. applyNormalMatrix( m ) {
  17881. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17882. _vector$7.fromBufferAttribute( this, i );
  17883. _vector$7.applyNormalMatrix( m );
  17884. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17885. }
  17886. return this;
  17887. }
  17888. /**
  17889. * Applies the given 4x4 matrix to the given attribute. Only works with
  17890. * item size `3` and with direction vectors.
  17891. *
  17892. * @param {Matrix4} m - The matrix to apply.
  17893. * @return {InterleavedBufferAttribute} A reference to this instance.
  17894. */
  17895. transformDirection( m ) {
  17896. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17897. _vector$7.fromBufferAttribute( this, i );
  17898. _vector$7.transformDirection( m );
  17899. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17900. }
  17901. return this;
  17902. }
  17903. /**
  17904. * Returns the given component of the vector at the given index.
  17905. *
  17906. * @param {number} index - The index into the buffer attribute.
  17907. * @param {number} component - The component index.
  17908. * @return {number} The returned value.
  17909. */
  17910. getComponent( index, component ) {
  17911. let value = this.array[ index * this.data.stride + this.offset + component ];
  17912. if ( this.normalized ) value = denormalize( value, this.array );
  17913. return value;
  17914. }
  17915. /**
  17916. * Sets the given value to the given component of the vector at the given index.
  17917. *
  17918. * @param {number} index - The index into the buffer attribute.
  17919. * @param {number} component - The component index.
  17920. * @param {number} value - The value to set.
  17921. * @return {InterleavedBufferAttribute} A reference to this instance.
  17922. */
  17923. setComponent( index, component, value ) {
  17924. if ( this.normalized ) value = normalize( value, this.array );
  17925. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17926. return this;
  17927. }
  17928. /**
  17929. * Sets the x component of the vector at the given index.
  17930. *
  17931. * @param {number} index - The index into the buffer attribute.
  17932. * @param {number} x - The value to set.
  17933. * @return {InterleavedBufferAttribute} A reference to this instance.
  17934. */
  17935. setX( index, x ) {
  17936. if ( this.normalized ) x = normalize( x, this.array );
  17937. this.data.array[ index * this.data.stride + this.offset ] = x;
  17938. return this;
  17939. }
  17940. /**
  17941. * Sets the y component of the vector at the given index.
  17942. *
  17943. * @param {number} index - The index into the buffer attribute.
  17944. * @param {number} y - The value to set.
  17945. * @return {InterleavedBufferAttribute} A reference to this instance.
  17946. */
  17947. setY( index, y ) {
  17948. if ( this.normalized ) y = normalize( y, this.array );
  17949. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17950. return this;
  17951. }
  17952. /**
  17953. * Sets the z component of the vector at the given index.
  17954. *
  17955. * @param {number} index - The index into the buffer attribute.
  17956. * @param {number} z - The value to set.
  17957. * @return {InterleavedBufferAttribute} A reference to this instance.
  17958. */
  17959. setZ( index, z ) {
  17960. if ( this.normalized ) z = normalize( z, this.array );
  17961. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17962. return this;
  17963. }
  17964. /**
  17965. * Sets the w component of the vector at the given index.
  17966. *
  17967. * @param {number} index - The index into the buffer attribute.
  17968. * @param {number} w - The value to set.
  17969. * @return {InterleavedBufferAttribute} A reference to this instance.
  17970. */
  17971. setW( index, w ) {
  17972. if ( this.normalized ) w = normalize( w, this.array );
  17973. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17974. return this;
  17975. }
  17976. /**
  17977. * Returns the x component of the vector at the given index.
  17978. *
  17979. * @param {number} index - The index into the buffer attribute.
  17980. * @return {number} The x component.
  17981. */
  17982. getX( index ) {
  17983. let x = this.data.array[ index * this.data.stride + this.offset ];
  17984. if ( this.normalized ) x = denormalize( x, this.array );
  17985. return x;
  17986. }
  17987. /**
  17988. * Returns the y component of the vector at the given index.
  17989. *
  17990. * @param {number} index - The index into the buffer attribute.
  17991. * @return {number} The y component.
  17992. */
  17993. getY( index ) {
  17994. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17995. if ( this.normalized ) y = denormalize( y, this.array );
  17996. return y;
  17997. }
  17998. /**
  17999. * Returns the z component of the vector at the given index.
  18000. *
  18001. * @param {number} index - The index into the buffer attribute.
  18002. * @return {number} The z component.
  18003. */
  18004. getZ( index ) {
  18005. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18006. if ( this.normalized ) z = denormalize( z, this.array );
  18007. return z;
  18008. }
  18009. /**
  18010. * Returns the w component of the vector at the given index.
  18011. *
  18012. * @param {number} index - The index into the buffer attribute.
  18013. * @return {number} The w component.
  18014. */
  18015. getW( index ) {
  18016. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18017. if ( this.normalized ) w = denormalize( w, this.array );
  18018. return w;
  18019. }
  18020. /**
  18021. * Sets the x and y component of the vector at the given index.
  18022. *
  18023. * @param {number} index - The index into the buffer attribute.
  18024. * @param {number} x - The value for the x component to set.
  18025. * @param {number} y - The value for the y component to set.
  18026. * @return {InterleavedBufferAttribute} A reference to this instance.
  18027. */
  18028. setXY( index, x, y ) {
  18029. index = index * this.data.stride + this.offset;
  18030. if ( this.normalized ) {
  18031. x = normalize( x, this.array );
  18032. y = normalize( y, this.array );
  18033. }
  18034. this.data.array[ index + 0 ] = x;
  18035. this.data.array[ index + 1 ] = y;
  18036. return this;
  18037. }
  18038. /**
  18039. * Sets the x, y and z component of the vector at the given index.
  18040. *
  18041. * @param {number} index - The index into the buffer attribute.
  18042. * @param {number} x - The value for the x component to set.
  18043. * @param {number} y - The value for the y component to set.
  18044. * @param {number} z - The value for the z component to set.
  18045. * @return {InterleavedBufferAttribute} A reference to this instance.
  18046. */
  18047. setXYZ( index, x, y, z ) {
  18048. index = index * this.data.stride + this.offset;
  18049. if ( this.normalized ) {
  18050. x = normalize( x, this.array );
  18051. y = normalize( y, this.array );
  18052. z = normalize( z, this.array );
  18053. }
  18054. this.data.array[ index + 0 ] = x;
  18055. this.data.array[ index + 1 ] = y;
  18056. this.data.array[ index + 2 ] = z;
  18057. return this;
  18058. }
  18059. /**
  18060. * Sets the x, y, z and w component of the vector at the given index.
  18061. *
  18062. * @param {number} index - The index into the buffer attribute.
  18063. * @param {number} x - The value for the x component to set.
  18064. * @param {number} y - The value for the y component to set.
  18065. * @param {number} z - The value for the z component to set.
  18066. * @param {number} w - The value for the w component to set.
  18067. * @return {InterleavedBufferAttribute} A reference to this instance.
  18068. */
  18069. setXYZW( index, x, y, z, w ) {
  18070. index = index * this.data.stride + this.offset;
  18071. if ( this.normalized ) {
  18072. x = normalize( x, this.array );
  18073. y = normalize( y, this.array );
  18074. z = normalize( z, this.array );
  18075. w = normalize( w, this.array );
  18076. }
  18077. this.data.array[ index + 0 ] = x;
  18078. this.data.array[ index + 1 ] = y;
  18079. this.data.array[ index + 2 ] = z;
  18080. this.data.array[ index + 3 ] = w;
  18081. return this;
  18082. }
  18083. /**
  18084. * Returns a new buffer attribute with copied values from this instance.
  18085. *
  18086. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18087. *
  18088. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  18089. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  18090. */
  18091. clone( data ) {
  18092. if ( data === undefined ) {
  18093. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18094. const array = [];
  18095. for ( let i = 0; i < this.count; i ++ ) {
  18096. const index = i * this.data.stride + this.offset;
  18097. for ( let j = 0; j < this.itemSize; j ++ ) {
  18098. array.push( this.data.array[ index + j ] );
  18099. }
  18100. }
  18101. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18102. } else {
  18103. if ( data.interleavedBuffers === undefined ) {
  18104. data.interleavedBuffers = {};
  18105. }
  18106. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18107. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18108. }
  18109. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18110. }
  18111. }
  18112. /**
  18113. * Serializes the buffer attribute into JSON.
  18114. *
  18115. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18116. *
  18117. * @param {Object} [data] - An optional value holding meta information about the serialization.
  18118. * @return {Object} A JSON object representing the serialized buffer attribute.
  18119. */
  18120. toJSON( data ) {
  18121. if ( data === undefined ) {
  18122. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18123. const array = [];
  18124. for ( let i = 0; i < this.count; i ++ ) {
  18125. const index = i * this.data.stride + this.offset;
  18126. for ( let j = 0; j < this.itemSize; j ++ ) {
  18127. array.push( this.data.array[ index + j ] );
  18128. }
  18129. }
  18130. // de-interleave data and save it as an ordinary buffer attribute for now
  18131. return {
  18132. itemSize: this.itemSize,
  18133. type: this.array.constructor.name,
  18134. array: array,
  18135. normalized: this.normalized
  18136. };
  18137. } else {
  18138. // save as true interleaved attribute
  18139. if ( data.interleavedBuffers === undefined ) {
  18140. data.interleavedBuffers = {};
  18141. }
  18142. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18143. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18144. }
  18145. return {
  18146. isInterleavedBufferAttribute: true,
  18147. itemSize: this.itemSize,
  18148. data: this.data.uuid,
  18149. offset: this.offset,
  18150. normalized: this.normalized
  18151. };
  18152. }
  18153. }
  18154. }
  18155. /**
  18156. * A material for rendering instances of {@link Sprite}.
  18157. *
  18158. * ```js
  18159. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  18160. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  18161. *
  18162. * const sprite = new THREE.Sprite( material );
  18163. * sprite.scale.set(200, 200, 1)
  18164. * scene.add( sprite );
  18165. * ```
  18166. *
  18167. * @augments Material
  18168. */
  18169. class SpriteMaterial extends Material {
  18170. /**
  18171. * Constructs a new sprite material.
  18172. *
  18173. * @param {Object} [parameters] - An object with one or more properties
  18174. * defining the material's appearance. Any property of the material
  18175. * (including any property from inherited materials) can be passed
  18176. * in here. Color values can be passed any type of value accepted
  18177. * by {@link Color#set}.
  18178. */
  18179. constructor( parameters ) {
  18180. super();
  18181. /**
  18182. * This flag can be used for type testing.
  18183. *
  18184. * @type {boolean}
  18185. * @readonly
  18186. * @default true
  18187. */
  18188. this.isSpriteMaterial = true;
  18189. this.type = 'SpriteMaterial';
  18190. /**
  18191. * Color of the material.
  18192. *
  18193. * @type {Color}
  18194. * @default (1,1,1)
  18195. */
  18196. this.color = new Color( 0xffffff );
  18197. /**
  18198. * The color map. May optionally include an alpha channel, typically combined
  18199. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  18200. * color is modulated by the diffuse `color`.
  18201. *
  18202. * @type {?Texture}
  18203. * @default null
  18204. */
  18205. this.map = null;
  18206. /**
  18207. * The alpha map is a grayscale texture that controls the opacity across the
  18208. * surface (black: fully transparent; white: fully opaque).
  18209. *
  18210. * Only the color of the texture is used, ignoring the alpha channel if one
  18211. * exists. For RGB and RGBA textures, the renderer will use the green channel
  18212. * when sampling this texture due to the extra bit of precision provided for
  18213. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  18214. * luminance/alpha textures will also still work as expected.
  18215. *
  18216. * @type {?Texture}
  18217. * @default null
  18218. */
  18219. this.alphaMap = null;
  18220. /**
  18221. * The rotation of the sprite in radians.
  18222. *
  18223. * @type {number}
  18224. * @default 0
  18225. */
  18226. this.rotation = 0;
  18227. /**
  18228. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18229. *
  18230. * @type {boolean}
  18231. * @default true
  18232. */
  18233. this.sizeAttenuation = true;
  18234. /**
  18235. * Overwritten since sprite materials are transparent
  18236. * by default.
  18237. *
  18238. * @type {boolean}
  18239. * @default true
  18240. */
  18241. this.transparent = true;
  18242. /**
  18243. * Whether the material is affected by fog or not.
  18244. *
  18245. * @type {boolean}
  18246. * @default true
  18247. */
  18248. this.fog = true;
  18249. this.setValues( parameters );
  18250. }
  18251. copy( source ) {
  18252. super.copy( source );
  18253. this.color.copy( source.color );
  18254. this.map = source.map;
  18255. this.alphaMap = source.alphaMap;
  18256. this.rotation = source.rotation;
  18257. this.sizeAttenuation = source.sizeAttenuation;
  18258. this.fog = source.fog;
  18259. return this;
  18260. }
  18261. }
  18262. let _geometry;
  18263. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18264. const _worldScale = /*@__PURE__*/ new Vector3();
  18265. const _mvPosition = /*@__PURE__*/ new Vector3();
  18266. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18267. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18268. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18269. const _vA = /*@__PURE__*/ new Vector3();
  18270. const _vB = /*@__PURE__*/ new Vector3();
  18271. const _vC = /*@__PURE__*/ new Vector3();
  18272. const _uvA = /*@__PURE__*/ new Vector2();
  18273. const _uvB = /*@__PURE__*/ new Vector2();
  18274. const _uvC = /*@__PURE__*/ new Vector2();
  18275. /**
  18276. * A sprite is a plane that always faces towards the camera, generally with a
  18277. * partially transparent texture applied.
  18278. *
  18279. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18280. * have no effect.
  18281. *
  18282. * ```js
  18283. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18284. * const material = new THREE.SpriteMaterial( { map: map } );
  18285. *
  18286. * const sprite = new THREE.Sprite( material );
  18287. * scene.add( sprite );
  18288. * ```
  18289. *
  18290. * @augments Object3D
  18291. */
  18292. class Sprite extends Object3D {
  18293. /**
  18294. * Constructs a new sprite.
  18295. *
  18296. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18297. */
  18298. constructor( material = new SpriteMaterial() ) {
  18299. super();
  18300. /**
  18301. * This flag can be used for type testing.
  18302. *
  18303. * @type {boolean}
  18304. * @readonly
  18305. * @default true
  18306. */
  18307. this.isSprite = true;
  18308. this.type = 'Sprite';
  18309. if ( _geometry === undefined ) {
  18310. _geometry = new BufferGeometry();
  18311. const float32Array = new Float32Array( [
  18312. -0.5, -0.5, 0, 0, 0,
  18313. 0.5, -0.5, 0, 1, 0,
  18314. 0.5, 0.5, 0, 1, 1,
  18315. -0.5, 0.5, 0, 0, 1
  18316. ] );
  18317. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18318. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18319. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18320. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18321. }
  18322. /**
  18323. * The sprite geometry.
  18324. *
  18325. * @type {BufferGeometry}
  18326. */
  18327. this.geometry = _geometry;
  18328. /**
  18329. * The sprite material.
  18330. *
  18331. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18332. */
  18333. this.material = material;
  18334. /**
  18335. * The sprite's anchor point, and the point around which the sprite rotates.
  18336. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18337. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18338. *
  18339. * @type {Vector2}
  18340. * @default (0.5,0.5)
  18341. */
  18342. this.center = new Vector2( 0.5, 0.5 );
  18343. /**
  18344. * The number of instances of this sprite.
  18345. * Can only be used with {@link WebGPURenderer}.
  18346. *
  18347. * @type {number}
  18348. * @default 1
  18349. */
  18350. this.count = 1;
  18351. }
  18352. /**
  18353. * Computes intersection points between a casted ray and this sprite.
  18354. *
  18355. * @param {Raycaster} raycaster - The raycaster.
  18356. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18357. */
  18358. raycast( raycaster, intersects ) {
  18359. if ( raycaster.camera === null ) {
  18360. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18361. }
  18362. _worldScale.setFromMatrixScale( this.matrixWorld );
  18363. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18364. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18365. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18366. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18367. _worldScale.multiplyScalar( - _mvPosition.z );
  18368. }
  18369. const rotation = this.material.rotation;
  18370. let sin, cos;
  18371. if ( rotation !== 0 ) {
  18372. cos = Math.cos( rotation );
  18373. sin = Math.sin( rotation );
  18374. }
  18375. const center = this.center;
  18376. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18377. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18378. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18379. _uvA.set( 0, 0 );
  18380. _uvB.set( 1, 0 );
  18381. _uvC.set( 1, 1 );
  18382. // check first triangle
  18383. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18384. if ( intersect === null ) {
  18385. // check second triangle
  18386. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18387. _uvB.set( 0, 1 );
  18388. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18389. if ( intersect === null ) {
  18390. return;
  18391. }
  18392. }
  18393. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18394. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18395. intersects.push( {
  18396. distance: distance,
  18397. point: _intersectPoint.clone(),
  18398. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18399. face: null,
  18400. object: this
  18401. } );
  18402. }
  18403. copy( source, recursive ) {
  18404. super.copy( source, recursive );
  18405. if ( source.center !== undefined ) this.center.copy( source.center );
  18406. this.material = source.material;
  18407. return this;
  18408. }
  18409. }
  18410. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18411. // compute position in camera space
  18412. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18413. // to check if rotation is not zero
  18414. if ( sin !== undefined ) {
  18415. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18416. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18417. } else {
  18418. _rotatedPosition.copy( _alignedPosition );
  18419. }
  18420. vertexPosition.copy( mvPosition );
  18421. vertexPosition.x += _rotatedPosition.x;
  18422. vertexPosition.y += _rotatedPosition.y;
  18423. // transform to world space
  18424. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18425. }
  18426. const _v1$2 = /*@__PURE__*/ new Vector3();
  18427. const _v2$1 = /*@__PURE__*/ new Vector3();
  18428. /**
  18429. * A component for providing a basic Level of Detail (LOD) mechanism.
  18430. *
  18431. * Every LOD level is associated with an object, and rendering can be switched
  18432. * between them at the distances specified. Typically you would create, say,
  18433. * three meshes, one for far away (low detail), one for mid range (medium
  18434. * detail) and one for close up (high detail).
  18435. *
  18436. * ```js
  18437. * const lod = new THREE.LOD();
  18438. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18439. *
  18440. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18441. * for( let i = 0; i < 3; i++ ) {
  18442. *
  18443. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18444. * const mesh = new THREE.Mesh( geometry, material );
  18445. * lod.addLevel( mesh, i * 75 );
  18446. *
  18447. * }
  18448. *
  18449. * scene.add( lod );
  18450. * ```
  18451. *
  18452. * @augments Object3D
  18453. */
  18454. class LOD extends Object3D {
  18455. /**
  18456. * Constructs a new LOD.
  18457. */
  18458. constructor() {
  18459. super();
  18460. /**
  18461. * This flag can be used for type testing.
  18462. *
  18463. * @type {boolean}
  18464. * @readonly
  18465. * @default true
  18466. */
  18467. this.isLOD = true;
  18468. /**
  18469. * The current LOD index.
  18470. *
  18471. * @private
  18472. * @type {number}
  18473. * @default 0
  18474. */
  18475. this._currentLevel = 0;
  18476. this.type = 'LOD';
  18477. Object.defineProperties( this, {
  18478. /**
  18479. * This array holds the LOD levels.
  18480. *
  18481. * @name LOD#levels
  18482. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18483. */
  18484. levels: {
  18485. enumerable: true,
  18486. value: []
  18487. }
  18488. } );
  18489. /**
  18490. * Whether the LOD object is updated automatically by the renderer per frame
  18491. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18492. * render loop by yourself.
  18493. *
  18494. * @type {boolean}
  18495. * @default true
  18496. */
  18497. this.autoUpdate = true;
  18498. }
  18499. copy( source ) {
  18500. super.copy( source, false );
  18501. const levels = source.levels;
  18502. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18503. const level = levels[ i ];
  18504. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18505. }
  18506. this.autoUpdate = source.autoUpdate;
  18507. return this;
  18508. }
  18509. /**
  18510. * Adds a mesh that will display at a certain distance and greater. Typically
  18511. * the further away the distance, the lower the detail on the mesh.
  18512. *
  18513. * @param {Object3D} object - The 3D object to display at this level.
  18514. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18515. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18516. * @return {LOD} A reference to this instance.
  18517. */
  18518. addLevel( object, distance = 0, hysteresis = 0 ) {
  18519. distance = Math.abs( distance );
  18520. const levels = this.levels;
  18521. let l;
  18522. for ( l = 0; l < levels.length; l ++ ) {
  18523. if ( distance < levels[ l ].distance ) {
  18524. break;
  18525. }
  18526. }
  18527. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18528. this.add( object );
  18529. return this;
  18530. }
  18531. /**
  18532. * Removes an existing level, based on the distance from the camera.
  18533. * Returns `true` when the level has been removed. Otherwise `false`.
  18534. *
  18535. * @param {number} distance - Distance of the level to remove.
  18536. * @return {boolean} Whether the level has been removed or not.
  18537. */
  18538. removeLevel( distance ) {
  18539. const levels = this.levels;
  18540. for ( let i = 0; i < levels.length; i ++ ) {
  18541. if ( levels[ i ].distance === distance ) {
  18542. const removedElements = levels.splice( i, 1 );
  18543. this.remove( removedElements[ 0 ].object );
  18544. return true;
  18545. }
  18546. }
  18547. return false;
  18548. }
  18549. /**
  18550. * Returns the currently active LOD level index.
  18551. *
  18552. * @return {number} The current active LOD level index.
  18553. */
  18554. getCurrentLevel() {
  18555. return this._currentLevel;
  18556. }
  18557. /**
  18558. * Returns a reference to the first 3D object that is greater than
  18559. * the given distance.
  18560. *
  18561. * @param {number} distance - The LOD distance.
  18562. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18563. */
  18564. getObjectForDistance( distance ) {
  18565. const levels = this.levels;
  18566. if ( levels.length > 0 ) {
  18567. let i, l;
  18568. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18569. let levelDistance = levels[ i ].distance;
  18570. if ( levels[ i ].object.visible ) {
  18571. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18572. }
  18573. if ( distance < levelDistance ) {
  18574. break;
  18575. }
  18576. }
  18577. return levels[ i - 1 ].object;
  18578. }
  18579. return null;
  18580. }
  18581. /**
  18582. * Computes intersection points between a casted ray and this LOD.
  18583. *
  18584. * @param {Raycaster} raycaster - The raycaster.
  18585. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18586. */
  18587. raycast( raycaster, intersects ) {
  18588. const levels = this.levels;
  18589. if ( levels.length > 0 ) {
  18590. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18591. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18592. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18593. }
  18594. }
  18595. /**
  18596. * Updates the LOD by computing which LOD level should be visible according
  18597. * to the current distance of the given camera.
  18598. *
  18599. * @param {Camera} camera - The camera the scene is rendered with.
  18600. */
  18601. update( camera ) {
  18602. const levels = this.levels;
  18603. if ( levels.length > 1 ) {
  18604. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18605. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18606. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18607. levels[ 0 ].object.visible = true;
  18608. let i, l;
  18609. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18610. let levelDistance = levels[ i ].distance;
  18611. if ( levels[ i ].object.visible ) {
  18612. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18613. }
  18614. if ( distance >= levelDistance ) {
  18615. levels[ i - 1 ].object.visible = false;
  18616. levels[ i ].object.visible = true;
  18617. } else {
  18618. break;
  18619. }
  18620. }
  18621. this._currentLevel = i - 1;
  18622. for ( ; i < l; i ++ ) {
  18623. levels[ i ].object.visible = false;
  18624. }
  18625. }
  18626. }
  18627. toJSON( meta ) {
  18628. const data = super.toJSON( meta );
  18629. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18630. data.object.levels = [];
  18631. const levels = this.levels;
  18632. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18633. const level = levels[ i ];
  18634. data.object.levels.push( {
  18635. object: level.object.uuid,
  18636. distance: level.distance,
  18637. hysteresis: level.hysteresis
  18638. } );
  18639. }
  18640. return data;
  18641. }
  18642. }
  18643. const _basePosition = /*@__PURE__*/ new Vector3();
  18644. const _skinIndex = /*@__PURE__*/ new Vector4();
  18645. const _skinWeight = /*@__PURE__*/ new Vector4();
  18646. const _vector3 = /*@__PURE__*/ new Vector3();
  18647. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18648. const _vertex = /*@__PURE__*/ new Vector3();
  18649. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18650. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18651. const _ray$2 = /*@__PURE__*/ new Ray();
  18652. /**
  18653. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18654. * vertices of the geometry with skinning/skeleton animation.
  18655. *
  18656. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18657. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18658. * vertex to a certain extend.
  18659. *
  18660. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18661. * or {@link FBXLoader } import respective models.
  18662. *
  18663. * @augments Mesh
  18664. * @demo scenes/bones-browser.html
  18665. */
  18666. class SkinnedMesh extends Mesh {
  18667. /**
  18668. * Constructs a new skinned mesh.
  18669. *
  18670. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18671. * @param {Material|Array<Material>} [material] - The mesh material.
  18672. */
  18673. constructor( geometry, material ) {
  18674. super( geometry, material );
  18675. /**
  18676. * This flag can be used for type testing.
  18677. *
  18678. * @type {boolean}
  18679. * @readonly
  18680. * @default true
  18681. */
  18682. this.isSkinnedMesh = true;
  18683. this.type = 'SkinnedMesh';
  18684. /**
  18685. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18686. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18687. * across multiple skinned meshes.
  18688. *
  18689. * @type {(AttachedBindMode|DetachedBindMode)}
  18690. * @default AttachedBindMode
  18691. */
  18692. this.bindMode = AttachedBindMode;
  18693. /**
  18694. * The base matrix that is used for the bound bone transforms.
  18695. *
  18696. * @type {Matrix4}
  18697. */
  18698. this.bindMatrix = new Matrix4();
  18699. /**
  18700. * The base matrix that is used for resetting the bound bone transforms.
  18701. *
  18702. * @type {Matrix4}
  18703. */
  18704. this.bindMatrixInverse = new Matrix4();
  18705. /**
  18706. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18707. *
  18708. * @type {?Box3}
  18709. * @default null
  18710. */
  18711. this.boundingBox = null;
  18712. /**
  18713. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18714. *
  18715. * @type {?Sphere}
  18716. * @default null
  18717. */
  18718. this.boundingSphere = null;
  18719. }
  18720. /**
  18721. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18722. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18723. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18724. * the current animation state.
  18725. */
  18726. computeBoundingBox() {
  18727. const geometry = this.geometry;
  18728. if ( this.boundingBox === null ) {
  18729. this.boundingBox = new Box3();
  18730. }
  18731. this.boundingBox.makeEmpty();
  18732. const positionAttribute = geometry.getAttribute( 'position' );
  18733. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18734. this.getVertexPosition( i, _vertex );
  18735. this.boundingBox.expandByPoint( _vertex );
  18736. }
  18737. }
  18738. /**
  18739. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18740. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18741. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18742. * per frame in order to reflect the current animation state.
  18743. */
  18744. computeBoundingSphere() {
  18745. const geometry = this.geometry;
  18746. if ( this.boundingSphere === null ) {
  18747. this.boundingSphere = new Sphere();
  18748. }
  18749. this.boundingSphere.makeEmpty();
  18750. const positionAttribute = geometry.getAttribute( 'position' );
  18751. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18752. this.getVertexPosition( i, _vertex );
  18753. this.boundingSphere.expandByPoint( _vertex );
  18754. }
  18755. }
  18756. copy( source, recursive ) {
  18757. super.copy( source, recursive );
  18758. this.bindMode = source.bindMode;
  18759. this.bindMatrix.copy( source.bindMatrix );
  18760. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18761. this.skeleton = source.skeleton;
  18762. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18763. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18764. return this;
  18765. }
  18766. raycast( raycaster, intersects ) {
  18767. const material = this.material;
  18768. const matrixWorld = this.matrixWorld;
  18769. if ( material === undefined ) return;
  18770. // test with bounding sphere in world space
  18771. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18772. _sphere$5.copy( this.boundingSphere );
  18773. _sphere$5.applyMatrix4( matrixWorld );
  18774. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18775. // convert ray to local space of skinned mesh
  18776. _inverseMatrix$2.copy( matrixWorld ).invert();
  18777. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18778. // test with bounding box in local space
  18779. if ( this.boundingBox !== null ) {
  18780. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18781. }
  18782. // test for intersections with geometry
  18783. this._computeIntersections( raycaster, intersects, _ray$2 );
  18784. }
  18785. getVertexPosition( index, target ) {
  18786. super.getVertexPosition( index, target );
  18787. this.applyBoneTransform( index, target );
  18788. return target;
  18789. }
  18790. /**
  18791. * Binds the given skeleton to the skinned mesh.
  18792. *
  18793. * @param {Skeleton} skeleton - The skeleton to bind.
  18794. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18795. * the skinned mesh's world matrix will be used instead.
  18796. */
  18797. bind( skeleton, bindMatrix ) {
  18798. this.skeleton = skeleton;
  18799. if ( bindMatrix === undefined ) {
  18800. this.updateMatrixWorld( true );
  18801. this.skeleton.calculateInverses();
  18802. bindMatrix = this.matrixWorld;
  18803. }
  18804. this.bindMatrix.copy( bindMatrix );
  18805. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18806. }
  18807. /**
  18808. * This method sets the skinned mesh in the rest pose).
  18809. */
  18810. pose() {
  18811. this.skeleton.pose();
  18812. }
  18813. /**
  18814. * Normalizes the skin weights which are defined as a buffer attribute
  18815. * in the skinned mesh's geometry.
  18816. */
  18817. normalizeSkinWeights() {
  18818. const vector = new Vector4();
  18819. const skinWeight = this.geometry.attributes.skinWeight;
  18820. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18821. vector.fromBufferAttribute( skinWeight, i );
  18822. const scale = 1.0 / vector.manhattanLength();
  18823. if ( scale !== Infinity ) {
  18824. vector.multiplyScalar( scale );
  18825. } else {
  18826. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18827. }
  18828. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18829. }
  18830. }
  18831. updateMatrixWorld( force ) {
  18832. super.updateMatrixWorld( force );
  18833. if ( this.bindMode === AttachedBindMode ) {
  18834. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18835. } else if ( this.bindMode === DetachedBindMode ) {
  18836. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18837. } else {
  18838. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18839. }
  18840. }
  18841. /**
  18842. * Applies the bone transform associated with the given index to the given
  18843. * vertex position. Returns the updated vector.
  18844. *
  18845. * @param {number} index - The vertex index.
  18846. * @param {Vector3} target - The target object that is used to store the method's result.
  18847. * the skinned mesh's world matrix will be used instead.
  18848. * @return {Vector3} The updated vertex position.
  18849. */
  18850. applyBoneTransform( index, target ) {
  18851. const skeleton = this.skeleton;
  18852. const geometry = this.geometry;
  18853. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18854. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18855. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18856. target.set( 0, 0, 0 );
  18857. for ( let i = 0; i < 4; i ++ ) {
  18858. const weight = _skinWeight.getComponent( i );
  18859. if ( weight !== 0 ) {
  18860. const boneIndex = _skinIndex.getComponent( i );
  18861. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18862. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18863. }
  18864. }
  18865. return target.applyMatrix4( this.bindMatrixInverse );
  18866. }
  18867. }
  18868. /**
  18869. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18870. * the {@link SkinnedMesh}.
  18871. *
  18872. * ```js
  18873. * const root = new THREE.Bone();
  18874. * const child = new THREE.Bone();
  18875. *
  18876. * root.add( child );
  18877. * child.position.y = 5;
  18878. * ```
  18879. *
  18880. * @augments Object3D
  18881. */
  18882. class Bone extends Object3D {
  18883. /**
  18884. * Constructs a new bone.
  18885. */
  18886. constructor() {
  18887. super();
  18888. /**
  18889. * This flag can be used for type testing.
  18890. *
  18891. * @type {boolean}
  18892. * @readonly
  18893. * @default true
  18894. */
  18895. this.isBone = true;
  18896. this.type = 'Bone';
  18897. }
  18898. }
  18899. /**
  18900. * Creates a texture directly from raw buffer data.
  18901. *
  18902. * The interpretation of the data depends on type and format: If the type is
  18903. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18904. * texel data. If the format is `RGBAFormat`, data needs four values for
  18905. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18906. *
  18907. * @augments Texture
  18908. */
  18909. class DataTexture extends Texture {
  18910. /**
  18911. * Constructs a new data texture.
  18912. *
  18913. * @param {?TypedArray} [data=null] - The buffer data.
  18914. * @param {number} [width=1] - The width of the texture.
  18915. * @param {number} [height=1] - The height of the texture.
  18916. * @param {number} [format=RGBAFormat] - The texture format.
  18917. * @param {number} [type=UnsignedByteType] - The texture type.
  18918. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18919. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18920. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18921. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18922. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18923. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18924. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18925. */
  18926. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18927. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18928. /**
  18929. * This flag can be used for type testing.
  18930. *
  18931. * @type {boolean}
  18932. * @readonly
  18933. * @default true
  18934. */
  18935. this.isDataTexture = true;
  18936. /**
  18937. * The image definition of a data texture.
  18938. *
  18939. * @type {{data:TypedArray,width:number,height:number}}
  18940. */
  18941. this.image = { data: data, width: width, height: height };
  18942. /**
  18943. * Whether to generate mipmaps (if possible) for a texture.
  18944. *
  18945. * Overwritten and set to `false` by default.
  18946. *
  18947. * @type {boolean}
  18948. * @default false
  18949. */
  18950. this.generateMipmaps = false;
  18951. /**
  18952. * If set to `true`, the texture is flipped along the vertical axis when
  18953. * uploaded to the GPU.
  18954. *
  18955. * Overwritten and set to `false` by default.
  18956. *
  18957. * @type {boolean}
  18958. * @default false
  18959. */
  18960. this.flipY = false;
  18961. /**
  18962. * Specifies the alignment requirements for the start of each pixel row in memory.
  18963. *
  18964. * Overwritten and set to `1` by default.
  18965. *
  18966. * @type {boolean}
  18967. * @default 1
  18968. */
  18969. this.unpackAlignment = 1;
  18970. }
  18971. }
  18972. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18973. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18974. /**
  18975. * Class for representing the armatures in `three.js`. The skeleton
  18976. * is defined by a hierarchy of bones.
  18977. *
  18978. * ```js
  18979. * const bones = [];
  18980. *
  18981. * const shoulder = new THREE.Bone();
  18982. * const elbow = new THREE.Bone();
  18983. * const hand = new THREE.Bone();
  18984. *
  18985. * shoulder.add( elbow );
  18986. * elbow.add( hand );
  18987. *
  18988. * bones.push( shoulder , elbow, hand);
  18989. *
  18990. * shoulder.position.y = -5;
  18991. * elbow.position.y = 0;
  18992. * hand.position.y = 5;
  18993. *
  18994. * const armSkeleton = new THREE.Skeleton( bones );
  18995. * ```
  18996. */
  18997. class Skeleton {
  18998. /**
  18999. * Constructs a new skeleton.
  19000. *
  19001. * @param {Array<Bone>} [bones] - An array of bones.
  19002. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  19003. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  19004. */
  19005. constructor( bones = [], boneInverses = [] ) {
  19006. this.uuid = generateUUID();
  19007. /**
  19008. * An array of bones defining the skeleton.
  19009. *
  19010. * @type {Array<Bone>}
  19011. */
  19012. this.bones = bones.slice( 0 );
  19013. /**
  19014. * An array of bone inverse matrices.
  19015. *
  19016. * @type {Array<Matrix4>}
  19017. */
  19018. this.boneInverses = boneInverses;
  19019. /**
  19020. * An array buffer holding the bone data.
  19021. * Input data for {@link Skeleton#boneTexture}.
  19022. *
  19023. * @type {?Float32Array}
  19024. * @default null
  19025. */
  19026. this.boneMatrices = null;
  19027. /**
  19028. * An array buffer holding the bone data of the previous frame.
  19029. * Required for computing velocity. Maintained in {@link SkinningNode}.
  19030. *
  19031. * @type {?Float32Array}
  19032. * @default null
  19033. */
  19034. this.previousBoneMatrices = null;
  19035. /**
  19036. * A texture holding the bone data for use
  19037. * in the vertex shader.
  19038. *
  19039. * @type {?DataTexture}
  19040. * @default null
  19041. */
  19042. this.boneTexture = null;
  19043. this.init();
  19044. }
  19045. /**
  19046. * Initializes the skeleton. This method gets automatically called by the constructor
  19047. * but depending on how the skeleton is created it might be necessary to call this method
  19048. * manually.
  19049. */
  19050. init() {
  19051. const bones = this.bones;
  19052. const boneInverses = this.boneInverses;
  19053. this.boneMatrices = new Float32Array( bones.length * 16 );
  19054. // calculate inverse bone matrices if necessary
  19055. if ( boneInverses.length === 0 ) {
  19056. this.calculateInverses();
  19057. } else {
  19058. // handle special case
  19059. if ( bones.length !== boneInverses.length ) {
  19060. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19061. this.boneInverses = [];
  19062. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19063. this.boneInverses.push( new Matrix4() );
  19064. }
  19065. }
  19066. }
  19067. }
  19068. /**
  19069. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  19070. * and fills it with new matrices.
  19071. */
  19072. calculateInverses() {
  19073. this.boneInverses.length = 0;
  19074. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19075. const inverse = new Matrix4();
  19076. if ( this.bones[ i ] ) {
  19077. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19078. }
  19079. this.boneInverses.push( inverse );
  19080. }
  19081. }
  19082. /**
  19083. * Resets the skeleton to the base pose.
  19084. */
  19085. pose() {
  19086. // recover the bind-time world matrices
  19087. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19088. const bone = this.bones[ i ];
  19089. if ( bone ) {
  19090. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19091. }
  19092. }
  19093. // compute the local matrices, positions, rotations and scales
  19094. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19095. const bone = this.bones[ i ];
  19096. if ( bone ) {
  19097. if ( bone.parent && bone.parent.isBone ) {
  19098. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19099. bone.matrix.multiply( bone.matrixWorld );
  19100. } else {
  19101. bone.matrix.copy( bone.matrixWorld );
  19102. }
  19103. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19104. }
  19105. }
  19106. }
  19107. /**
  19108. * Resets the skeleton to the base pose.
  19109. */
  19110. update() {
  19111. const bones = this.bones;
  19112. const boneInverses = this.boneInverses;
  19113. const boneMatrices = this.boneMatrices;
  19114. const boneTexture = this.boneTexture;
  19115. // flatten bone matrices to array
  19116. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19117. // compute the offset between the current and the original transform
  19118. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  19119. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19120. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19121. }
  19122. if ( boneTexture !== null ) {
  19123. boneTexture.needsUpdate = true;
  19124. }
  19125. }
  19126. /**
  19127. * Returns a new skeleton with copied values from this instance.
  19128. *
  19129. * @return {Skeleton} A clone of this instance.
  19130. */
  19131. clone() {
  19132. return new Skeleton( this.bones, this.boneInverses );
  19133. }
  19134. /**
  19135. * Computes a data texture for passing bone data to the vertex shader.
  19136. *
  19137. * @return {Skeleton} A reference of this instance.
  19138. */
  19139. computeBoneTexture() {
  19140. // layout (1 matrix = 4 pixels)
  19141. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19142. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19143. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19144. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19145. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19146. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19147. size = Math.ceil( size / 4 ) * 4;
  19148. size = Math.max( size, 4 );
  19149. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19150. boneMatrices.set( this.boneMatrices ); // copy current values
  19151. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19152. boneTexture.needsUpdate = true;
  19153. this.boneMatrices = boneMatrices;
  19154. this.boneTexture = boneTexture;
  19155. return this;
  19156. }
  19157. /**
  19158. * Searches through the skeleton's bone array and returns the first with a
  19159. * matching name.
  19160. *
  19161. * @param {string} name - The name of the bone.
  19162. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  19163. */
  19164. getBoneByName( name ) {
  19165. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19166. const bone = this.bones[ i ];
  19167. if ( bone.name === name ) {
  19168. return bone;
  19169. }
  19170. }
  19171. return undefined;
  19172. }
  19173. /**
  19174. * Frees the GPU-related resources allocated by this instance. Call this
  19175. * method whenever this instance is no longer used in your app.
  19176. */
  19177. dispose( ) {
  19178. if ( this.boneTexture !== null ) {
  19179. this.boneTexture.dispose();
  19180. this.boneTexture = null;
  19181. }
  19182. }
  19183. /**
  19184. * Setups the skeleton by the given JSON and bones.
  19185. *
  19186. * @param {Object} json - The skeleton as serialized JSON.
  19187. * @param {Object<string, Bone>} bones - An array of bones.
  19188. * @return {Skeleton} A reference of this instance.
  19189. */
  19190. fromJSON( json, bones ) {
  19191. this.uuid = json.uuid;
  19192. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19193. const uuid = json.bones[ i ];
  19194. let bone = bones[ uuid ];
  19195. if ( bone === undefined ) {
  19196. warn( 'Skeleton: No bone found with UUID:', uuid );
  19197. bone = new Bone();
  19198. }
  19199. this.bones.push( bone );
  19200. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19201. }
  19202. this.init();
  19203. return this;
  19204. }
  19205. /**
  19206. * Serializes the skeleton into JSON.
  19207. *
  19208. * @return {Object} A JSON object representing the serialized skeleton.
  19209. * @see {@link ObjectLoader#parse}
  19210. */
  19211. toJSON() {
  19212. const data = {
  19213. metadata: {
  19214. version: 4.7,
  19215. type: 'Skeleton',
  19216. generator: 'Skeleton.toJSON'
  19217. },
  19218. bones: [],
  19219. boneInverses: []
  19220. };
  19221. data.uuid = this.uuid;
  19222. const bones = this.bones;
  19223. const boneInverses = this.boneInverses;
  19224. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19225. const bone = bones[ i ];
  19226. data.bones.push( bone.uuid );
  19227. const boneInverse = boneInverses[ i ];
  19228. data.boneInverses.push( boneInverse.toArray() );
  19229. }
  19230. return data;
  19231. }
  19232. }
  19233. /**
  19234. * An instanced version of a buffer attribute.
  19235. *
  19236. * @augments BufferAttribute
  19237. */
  19238. class InstancedBufferAttribute extends BufferAttribute {
  19239. /**
  19240. * Constructs a new instanced buffer attribute.
  19241. *
  19242. * @param {TypedArray} array - The array holding the attribute data.
  19243. * @param {number} itemSize - The item size.
  19244. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19245. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19246. */
  19247. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19248. super( array, itemSize, normalized );
  19249. /**
  19250. * This flag can be used for type testing.
  19251. *
  19252. * @type {boolean}
  19253. * @readonly
  19254. * @default true
  19255. */
  19256. this.isInstancedBufferAttribute = true;
  19257. /**
  19258. * Defines how often a value of this buffer attribute should be repeated. A
  19259. * value of one means that each value of the instanced attribute is used for
  19260. * a single instance. A value of two means that each value is used for two
  19261. * consecutive instances (and so on).
  19262. *
  19263. * @type {number}
  19264. * @default 1
  19265. */
  19266. this.meshPerAttribute = meshPerAttribute;
  19267. }
  19268. copy( source ) {
  19269. super.copy( source );
  19270. this.meshPerAttribute = source.meshPerAttribute;
  19271. return this;
  19272. }
  19273. toJSON() {
  19274. const data = super.toJSON();
  19275. data.meshPerAttribute = this.meshPerAttribute;
  19276. data.isInstancedBufferAttribute = true;
  19277. return data;
  19278. }
  19279. }
  19280. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19281. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19282. const _instanceIntersects = [];
  19283. const _box3 = /*@__PURE__*/ new Box3();
  19284. const _identity = /*@__PURE__*/ new Matrix4();
  19285. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19286. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19287. /**
  19288. * A special version of a mesh with instanced rendering support. Use
  19289. * this class if you have to render a large number of objects with the same
  19290. * geometry and material(s) but with different world transformations. The usage
  19291. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19292. * improve the overall rendering performance in your application.
  19293. *
  19294. * @augments Mesh
  19295. */
  19296. class InstancedMesh extends Mesh {
  19297. /**
  19298. * Constructs a new instanced mesh.
  19299. *
  19300. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19301. * @param {Material|Array<Material>} [material] - The mesh material.
  19302. * @param {number} count - The number of instances.
  19303. */
  19304. constructor( geometry, material, count ) {
  19305. super( geometry, material );
  19306. /**
  19307. * This flag can be used for type testing.
  19308. *
  19309. * @type {boolean}
  19310. * @readonly
  19311. * @default true
  19312. */
  19313. this.isInstancedMesh = true;
  19314. /**
  19315. * Represents the local transformation of all instances. You have to set its
  19316. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19317. * via {@link InstancedMesh#setMatrixAt}.
  19318. *
  19319. * @type {InstancedBufferAttribute}
  19320. */
  19321. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19322. /**
  19323. * Represents the local transformation of all instances of the previous frame.
  19324. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19325. *
  19326. * @type {?InstancedBufferAttribute}
  19327. * @default null
  19328. */
  19329. this.previousInstanceMatrix = null;
  19330. /**
  19331. * Represents the color of all instances. You have to set its
  19332. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19333. * via {@link InstancedMesh#setColorAt}.
  19334. *
  19335. * @type {?InstancedBufferAttribute}
  19336. * @default null
  19337. */
  19338. this.instanceColor = null;
  19339. /**
  19340. * Represents the morph target weights of all instances. You have to set its
  19341. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19342. * via {@link InstancedMesh#setMorphAt}.
  19343. *
  19344. * @type {?DataTexture}
  19345. * @default null
  19346. */
  19347. this.morphTexture = null;
  19348. /**
  19349. * The number of instances.
  19350. *
  19351. * @type {number}
  19352. */
  19353. this.count = count;
  19354. /**
  19355. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19356. *
  19357. * @type {?Box3}
  19358. * @default null
  19359. */
  19360. this.boundingBox = null;
  19361. /**
  19362. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19363. *
  19364. * @type {?Sphere}
  19365. * @default null
  19366. */
  19367. this.boundingSphere = null;
  19368. for ( let i = 0; i < count; i ++ ) {
  19369. this.setMatrixAt( i, _identity );
  19370. }
  19371. }
  19372. /**
  19373. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19374. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19375. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19376. */
  19377. computeBoundingBox() {
  19378. const geometry = this.geometry;
  19379. const count = this.count;
  19380. if ( this.boundingBox === null ) {
  19381. this.boundingBox = new Box3();
  19382. }
  19383. if ( geometry.boundingBox === null ) {
  19384. geometry.computeBoundingBox();
  19385. }
  19386. this.boundingBox.makeEmpty();
  19387. for ( let i = 0; i < count; i ++ ) {
  19388. this.getMatrixAt( i, _instanceLocalMatrix );
  19389. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19390. this.boundingBox.union( _box3 );
  19391. }
  19392. }
  19393. /**
  19394. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19395. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19396. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19397. */
  19398. computeBoundingSphere() {
  19399. const geometry = this.geometry;
  19400. const count = this.count;
  19401. if ( this.boundingSphere === null ) {
  19402. this.boundingSphere = new Sphere();
  19403. }
  19404. if ( geometry.boundingSphere === null ) {
  19405. geometry.computeBoundingSphere();
  19406. }
  19407. this.boundingSphere.makeEmpty();
  19408. for ( let i = 0; i < count; i ++ ) {
  19409. this.getMatrixAt( i, _instanceLocalMatrix );
  19410. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19411. this.boundingSphere.union( _sphere$4 );
  19412. }
  19413. }
  19414. copy( source, recursive ) {
  19415. super.copy( source, recursive );
  19416. this.instanceMatrix.copy( source.instanceMatrix );
  19417. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19418. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19419. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19420. this.count = source.count;
  19421. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19422. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19423. return this;
  19424. }
  19425. /**
  19426. * Gets the color of the defined instance.
  19427. *
  19428. * @param {number} index - The instance index.
  19429. * @param {Color} color - The target object that is used to store the method's result.
  19430. */
  19431. getColorAt( index, color ) {
  19432. color.fromArray( this.instanceColor.array, index * 3 );
  19433. }
  19434. /**
  19435. * Gets the local transformation matrix of the defined instance.
  19436. *
  19437. * @param {number} index - The instance index.
  19438. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19439. */
  19440. getMatrixAt( index, matrix ) {
  19441. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19442. }
  19443. /**
  19444. * Gets the morph target weights of the defined instance.
  19445. *
  19446. * @param {number} index - The instance index.
  19447. * @param {Mesh} object - The target object that is used to store the method's result.
  19448. */
  19449. getMorphAt( index, object ) {
  19450. const objectInfluences = object.morphTargetInfluences;
  19451. const array = this.morphTexture.source.data.data;
  19452. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19453. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19454. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19455. objectInfluences[ i ] = array[ dataIndex + i ];
  19456. }
  19457. }
  19458. raycast( raycaster, intersects ) {
  19459. const matrixWorld = this.matrixWorld;
  19460. const raycastTimes = this.count;
  19461. _mesh$1.geometry = this.geometry;
  19462. _mesh$1.material = this.material;
  19463. if ( _mesh$1.material === undefined ) return;
  19464. // test with bounding sphere first
  19465. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19466. _sphere$4.copy( this.boundingSphere );
  19467. _sphere$4.applyMatrix4( matrixWorld );
  19468. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19469. // now test each instance
  19470. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19471. // calculate the world matrix for each instance
  19472. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19473. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19474. // the mesh represents this single instance
  19475. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19476. _mesh$1.raycast( raycaster, _instanceIntersects );
  19477. // process the result of raycast
  19478. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19479. const intersect = _instanceIntersects[ i ];
  19480. intersect.instanceId = instanceId;
  19481. intersect.object = this;
  19482. intersects.push( intersect );
  19483. }
  19484. _instanceIntersects.length = 0;
  19485. }
  19486. }
  19487. /**
  19488. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19489. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19490. *
  19491. * @param {number} index - The instance index.
  19492. * @param {Color} color - The instance color.
  19493. */
  19494. setColorAt( index, color ) {
  19495. if ( this.instanceColor === null ) {
  19496. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19497. }
  19498. color.toArray( this.instanceColor.array, index * 3 );
  19499. }
  19500. /**
  19501. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19502. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19503. *
  19504. * @param {number} index - The instance index.
  19505. * @param {Matrix4} matrix - The local transformation.
  19506. */
  19507. setMatrixAt( index, matrix ) {
  19508. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19509. }
  19510. /**
  19511. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19512. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19513. *
  19514. * @param {number} index - The instance index.
  19515. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19516. * of a single instance.
  19517. */
  19518. setMorphAt( index, object ) {
  19519. const objectInfluences = object.morphTargetInfluences;
  19520. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19521. if ( this.morphTexture === null ) {
  19522. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19523. }
  19524. const array = this.morphTexture.source.data.data;
  19525. let morphInfluencesSum = 0;
  19526. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19527. morphInfluencesSum += objectInfluences[ i ];
  19528. }
  19529. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19530. const dataIndex = len * index;
  19531. array[ dataIndex ] = morphBaseInfluence;
  19532. array.set( objectInfluences, dataIndex + 1 );
  19533. }
  19534. updateMorphTargets() {
  19535. }
  19536. /**
  19537. * Frees the GPU-related resources allocated by this instance. Call this
  19538. * method whenever this instance is no longer used in your app.
  19539. */
  19540. dispose() {
  19541. this.dispatchEvent( { type: 'dispose' } );
  19542. if ( this.morphTexture !== null ) {
  19543. this.morphTexture.dispose();
  19544. this.morphTexture = null;
  19545. }
  19546. }
  19547. }
  19548. const _vector1 = /*@__PURE__*/ new Vector3();
  19549. const _vector2 = /*@__PURE__*/ new Vector3();
  19550. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19551. /**
  19552. * A two dimensional surface that extends infinitely in 3D space, represented
  19553. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19554. * by a unit length normal vector and a constant.
  19555. */
  19556. class Plane {
  19557. /**
  19558. * Constructs a new plane.
  19559. *
  19560. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19561. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19562. */
  19563. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19564. /**
  19565. * This flag can be used for type testing.
  19566. *
  19567. * @type {boolean}
  19568. * @readonly
  19569. * @default true
  19570. */
  19571. this.isPlane = true;
  19572. /**
  19573. * A unit length vector defining the normal of the plane.
  19574. *
  19575. * @type {Vector3}
  19576. */
  19577. this.normal = normal;
  19578. /**
  19579. * The signed distance from the origin to the plane.
  19580. *
  19581. * @type {number}
  19582. * @default 0
  19583. */
  19584. this.constant = constant;
  19585. }
  19586. /**
  19587. * Sets the plane components by copying the given values.
  19588. *
  19589. * @param {Vector3} normal - The normal.
  19590. * @param {number} constant - The constant.
  19591. * @return {Plane} A reference to this plane.
  19592. */
  19593. set( normal, constant ) {
  19594. this.normal.copy( normal );
  19595. this.constant = constant;
  19596. return this;
  19597. }
  19598. /**
  19599. * Sets the plane components by defining `x`, `y`, `z` as the
  19600. * plane normal and `w` as the constant.
  19601. *
  19602. * @param {number} x - The value for the normal's x component.
  19603. * @param {number} y - The value for the normal's y component.
  19604. * @param {number} z - The value for the normal's z component.
  19605. * @param {number} w - The constant value.
  19606. * @return {Plane} A reference to this plane.
  19607. */
  19608. setComponents( x, y, z, w ) {
  19609. this.normal.set( x, y, z );
  19610. this.constant = w;
  19611. return this;
  19612. }
  19613. /**
  19614. * Sets the plane from the given normal and coplanar point (that is a point
  19615. * that lies onto the plane).
  19616. *
  19617. * @param {Vector3} normal - The normal.
  19618. * @param {Vector3} point - A coplanar point.
  19619. * @return {Plane} A reference to this plane.
  19620. */
  19621. setFromNormalAndCoplanarPoint( normal, point ) {
  19622. this.normal.copy( normal );
  19623. this.constant = - point.dot( this.normal );
  19624. return this;
  19625. }
  19626. /**
  19627. * Sets the plane from three coplanar points. The winding order is
  19628. * assumed to be counter-clockwise, and determines the direction of
  19629. * the plane normal.
  19630. *
  19631. * @param {Vector3} a - The first coplanar point.
  19632. * @param {Vector3} b - The second coplanar point.
  19633. * @param {Vector3} c - The third coplanar point.
  19634. * @return {Plane} A reference to this plane.
  19635. */
  19636. setFromCoplanarPoints( a, b, c ) {
  19637. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19638. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19639. this.setFromNormalAndCoplanarPoint( normal, a );
  19640. return this;
  19641. }
  19642. /**
  19643. * Copies the values of the given plane to this instance.
  19644. *
  19645. * @param {Plane} plane - The plane to copy.
  19646. * @return {Plane} A reference to this plane.
  19647. */
  19648. copy( plane ) {
  19649. this.normal.copy( plane.normal );
  19650. this.constant = plane.constant;
  19651. return this;
  19652. }
  19653. /**
  19654. * Normalizes the plane normal and adjusts the constant accordingly.
  19655. *
  19656. * @return {Plane} A reference to this plane.
  19657. */
  19658. normalize() {
  19659. // Note: will lead to a divide by zero if the plane is invalid.
  19660. const inverseNormalLength = 1.0 / this.normal.length();
  19661. this.normal.multiplyScalar( inverseNormalLength );
  19662. this.constant *= inverseNormalLength;
  19663. return this;
  19664. }
  19665. /**
  19666. * Negates both the plane normal and the constant.
  19667. *
  19668. * @return {Plane} A reference to this plane.
  19669. */
  19670. negate() {
  19671. this.constant *= -1;
  19672. this.normal.negate();
  19673. return this;
  19674. }
  19675. /**
  19676. * Returns the signed distance from the given point to this plane.
  19677. *
  19678. * @param {Vector3} point - The point to compute the distance for.
  19679. * @return {number} The signed distance.
  19680. */
  19681. distanceToPoint( point ) {
  19682. return this.normal.dot( point ) + this.constant;
  19683. }
  19684. /**
  19685. * Returns the signed distance from the given sphere to this plane.
  19686. *
  19687. * @param {Sphere} sphere - The sphere to compute the distance for.
  19688. * @return {number} The signed distance.
  19689. */
  19690. distanceToSphere( sphere ) {
  19691. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19692. }
  19693. /**
  19694. * Projects a the given point onto the plane.
  19695. *
  19696. * @param {Vector3} point - The point to project.
  19697. * @param {Vector3} target - The target vector that is used to store the method's result.
  19698. * @return {Vector3} The projected point on the plane.
  19699. */
  19700. projectPoint( point, target ) {
  19701. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19702. }
  19703. /**
  19704. * Returns the intersection point of the passed line and the plane. Returns
  19705. * `null` if the line does not intersect. Returns the line's starting point if
  19706. * the line is coplanar with the plane.
  19707. *
  19708. * @param {Line3} line - The line to compute the intersection for.
  19709. * @param {Vector3} target - The target vector that is used to store the method's result.
  19710. * @return {?Vector3} The intersection point.
  19711. */
  19712. intersectLine( line, target ) {
  19713. const direction = line.delta( _vector1 );
  19714. const denominator = this.normal.dot( direction );
  19715. if ( denominator === 0 ) {
  19716. // line is coplanar, return origin
  19717. if ( this.distanceToPoint( line.start ) === 0 ) {
  19718. return target.copy( line.start );
  19719. }
  19720. // Unsure if this is the correct method to handle this case.
  19721. return null;
  19722. }
  19723. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19724. if ( t < 0 || t > 1 ) {
  19725. return null;
  19726. }
  19727. return target.copy( line.start ).addScaledVector( direction, t );
  19728. }
  19729. /**
  19730. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19731. *
  19732. * @param {Line3} line - The line to test.
  19733. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19734. */
  19735. intersectsLine( line ) {
  19736. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19737. const startSign = this.distanceToPoint( line.start );
  19738. const endSign = this.distanceToPoint( line.end );
  19739. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19740. }
  19741. /**
  19742. * Returns `true` if the given bounding box intersects with the plane.
  19743. *
  19744. * @param {Box3} box - The bounding box to test.
  19745. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19746. */
  19747. intersectsBox( box ) {
  19748. return box.intersectsPlane( this );
  19749. }
  19750. /**
  19751. * Returns `true` if the given bounding sphere intersects with the plane.
  19752. *
  19753. * @param {Sphere} sphere - The bounding sphere to test.
  19754. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19755. */
  19756. intersectsSphere( sphere ) {
  19757. return sphere.intersectsPlane( this );
  19758. }
  19759. /**
  19760. * Returns a coplanar vector to the plane, by calculating the
  19761. * projection of the normal at the origin onto the plane.
  19762. *
  19763. * @param {Vector3} target - The target vector that is used to store the method's result.
  19764. * @return {Vector3} The coplanar point.
  19765. */
  19766. coplanarPoint( target ) {
  19767. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19768. }
  19769. /**
  19770. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19771. *
  19772. * The optional normal matrix can be pre-computed like so:
  19773. * ```js
  19774. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19775. * ```
  19776. *
  19777. * @param {Matrix4} matrix - The transformation matrix.
  19778. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19779. * @return {Plane} A reference to this plane.
  19780. */
  19781. applyMatrix4( matrix, optionalNormalMatrix ) {
  19782. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19783. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19784. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19785. this.constant = - referencePoint.dot( normal );
  19786. return this;
  19787. }
  19788. /**
  19789. * Translates the plane by the distance defined by the given offset vector.
  19790. * Note that this only affects the plane constant and will not affect the normal vector.
  19791. *
  19792. * @param {Vector3} offset - The offset vector.
  19793. * @return {Plane} A reference to this plane.
  19794. */
  19795. translate( offset ) {
  19796. this.constant -= offset.dot( this.normal );
  19797. return this;
  19798. }
  19799. /**
  19800. * Returns `true` if this plane is equal with the given one.
  19801. *
  19802. * @param {Plane} plane - The plane to test for equality.
  19803. * @return {boolean} Whether this plane is equal with the given one.
  19804. */
  19805. equals( plane ) {
  19806. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19807. }
  19808. /**
  19809. * Returns a new plane with copied values from this instance.
  19810. *
  19811. * @return {Plane} A clone of this instance.
  19812. */
  19813. clone() {
  19814. return new this.constructor().copy( this );
  19815. }
  19816. }
  19817. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19818. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19819. const _vector$6 = /*@__PURE__*/ new Vector3();
  19820. /**
  19821. * Frustums are used to determine what is inside the camera's field of view.
  19822. * They help speed up the rendering process - objects which lie outside a camera's
  19823. * frustum can safely be excluded from rendering.
  19824. *
  19825. * This class is mainly intended for use internally by a renderer.
  19826. */
  19827. class Frustum {
  19828. /**
  19829. * Constructs a new frustum.
  19830. *
  19831. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19832. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19833. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19834. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19835. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19836. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19837. */
  19838. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19839. /**
  19840. * This array holds the planes that enclose the frustum.
  19841. *
  19842. * @type {Array<Plane>}
  19843. */
  19844. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19845. }
  19846. /**
  19847. * Sets the frustum planes by copying the given planes.
  19848. *
  19849. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19850. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19851. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19852. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19853. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19854. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19855. * @return {Frustum} A reference to this frustum.
  19856. */
  19857. set( p0, p1, p2, p3, p4, p5 ) {
  19858. const planes = this.planes;
  19859. planes[ 0 ].copy( p0 );
  19860. planes[ 1 ].copy( p1 );
  19861. planes[ 2 ].copy( p2 );
  19862. planes[ 3 ].copy( p3 );
  19863. planes[ 4 ].copy( p4 );
  19864. planes[ 5 ].copy( p5 );
  19865. return this;
  19866. }
  19867. /**
  19868. * Copies the values of the given frustum to this instance.
  19869. *
  19870. * @param {Frustum} frustum - The frustum to copy.
  19871. * @return {Frustum} A reference to this frustum.
  19872. */
  19873. copy( frustum ) {
  19874. const planes = this.planes;
  19875. for ( let i = 0; i < 6; i ++ ) {
  19876. planes[ i ].copy( frustum.planes[ i ] );
  19877. }
  19878. return this;
  19879. }
  19880. /**
  19881. * Sets the frustum planes from the given projection matrix.
  19882. *
  19883. * @param {Matrix4} m - The projection matrix.
  19884. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19885. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19886. * @return {Frustum} A reference to this frustum.
  19887. */
  19888. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19889. const planes = this.planes;
  19890. const me = m.elements;
  19891. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19892. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19893. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19894. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19895. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19896. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19897. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19898. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19899. if ( reversedDepth ) {
  19900. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19901. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19902. } else {
  19903. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19904. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19905. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19906. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19907. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19908. } else {
  19909. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19910. }
  19911. }
  19912. return this;
  19913. }
  19914. /**
  19915. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19916. *
  19917. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19918. *
  19919. * @param {Object3D} object - The 3D object to test.
  19920. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19921. */
  19922. intersectsObject( object ) {
  19923. if ( object.boundingSphere !== undefined ) {
  19924. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19925. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19926. } else {
  19927. const geometry = object.geometry;
  19928. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19929. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19930. }
  19931. return this.intersectsSphere( _sphere$3 );
  19932. }
  19933. /**
  19934. * Returns `true` if the given sprite is intersecting this frustum.
  19935. *
  19936. * @param {Sprite} sprite - The sprite to test.
  19937. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19938. */
  19939. intersectsSprite( sprite ) {
  19940. _sphere$3.center.set( 0, 0, 0 );
  19941. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19942. _sphere$3.radius = 0.7071067811865476 + offset;
  19943. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19944. return this.intersectsSphere( _sphere$3 );
  19945. }
  19946. /**
  19947. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19948. *
  19949. * @param {Sphere} sphere - The bounding sphere to test.
  19950. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19951. */
  19952. intersectsSphere( sphere ) {
  19953. const planes = this.planes;
  19954. const center = sphere.center;
  19955. const negRadius = - sphere.radius;
  19956. for ( let i = 0; i < 6; i ++ ) {
  19957. const distance = planes[ i ].distanceToPoint( center );
  19958. if ( distance < negRadius ) {
  19959. return false;
  19960. }
  19961. }
  19962. return true;
  19963. }
  19964. /**
  19965. * Returns `true` if the given bounding box is intersecting this frustum.
  19966. *
  19967. * @param {Box3} box - The bounding box to test.
  19968. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19969. */
  19970. intersectsBox( box ) {
  19971. const planes = this.planes;
  19972. for ( let i = 0; i < 6; i ++ ) {
  19973. const plane = planes[ i ];
  19974. // corner at max distance
  19975. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19976. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19977. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19978. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19979. return false;
  19980. }
  19981. }
  19982. return true;
  19983. }
  19984. /**
  19985. * Returns `true` if the given point lies within the frustum.
  19986. *
  19987. * @param {Vector3} point - The point to test.
  19988. * @return {boolean} Whether the point lies within this frustum or not.
  19989. */
  19990. containsPoint( point ) {
  19991. const planes = this.planes;
  19992. for ( let i = 0; i < 6; i ++ ) {
  19993. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19994. return false;
  19995. }
  19996. }
  19997. return true;
  19998. }
  19999. /**
  20000. * Returns a new frustum with copied values from this instance.
  20001. *
  20002. * @return {Frustum} A clone of this instance.
  20003. */
  20004. clone() {
  20005. return new this.constructor().copy( this );
  20006. }
  20007. }
  20008. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  20009. const _frustum$1 = /*@__PURE__*/ new Frustum();
  20010. /**
  20011. * FrustumArray is used to determine if an object is visible in at least one camera
  20012. * from an array of cameras. This is particularly useful for multi-view renderers.
  20013. */
  20014. class FrustumArray {
  20015. /**
  20016. * Constructs a new frustum array.
  20017. *
  20018. */
  20019. constructor() {
  20020. /**
  20021. * The coordinate system to use.
  20022. *
  20023. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  20024. * @default WebGLCoordinateSystem
  20025. */
  20026. this.coordinateSystem = WebGLCoordinateSystem;
  20027. }
  20028. /**
  20029. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  20030. * from the camera array.
  20031. *
  20032. * @param {Object3D} object - The 3D object to test.
  20033. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20034. * @return {boolean} Whether the 3D object is visible in any camera.
  20035. */
  20036. intersectsObject( object, cameraArray ) {
  20037. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  20038. return false;
  20039. }
  20040. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20041. const camera = cameraArray.cameras[ i ];
  20042. _projScreenMatrix$2.multiplyMatrices(
  20043. camera.projectionMatrix,
  20044. camera.matrixWorldInverse
  20045. );
  20046. _frustum$1.setFromProjectionMatrix(
  20047. _projScreenMatrix$2,
  20048. camera.coordinateSystem,
  20049. camera.reversedDepth
  20050. );
  20051. if ( _frustum$1.intersectsObject( object ) ) {
  20052. return true; // Object is visible in at least one camera
  20053. }
  20054. }
  20055. return false; // Not visible in any camera
  20056. }
  20057. /**
  20058. * Returns `true` if the given sprite is intersecting any frustum
  20059. * from the camera array.
  20060. *
  20061. * @param {Sprite} sprite - The sprite to test.
  20062. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20063. * @return {boolean} Whether the sprite is visible in any camera.
  20064. */
  20065. intersectsSprite( sprite, cameraArray ) {
  20066. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20067. return false;
  20068. }
  20069. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20070. const camera = cameraArray.cameras[ i ];
  20071. _projScreenMatrix$2.multiplyMatrices(
  20072. camera.projectionMatrix,
  20073. camera.matrixWorldInverse
  20074. );
  20075. _frustum$1.setFromProjectionMatrix(
  20076. _projScreenMatrix$2,
  20077. camera.coordinateSystem,
  20078. camera.reversedDepth
  20079. );
  20080. if ( _frustum$1.intersectsSprite( sprite ) ) {
  20081. return true; // Sprite is visible in at least one camera
  20082. }
  20083. }
  20084. return false; // Not visible in any camera
  20085. }
  20086. /**
  20087. * Returns `true` if the given bounding sphere is intersecting any frustum
  20088. * from the camera array.
  20089. *
  20090. * @param {Sphere} sphere - The bounding sphere to test.
  20091. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20092. * @return {boolean} Whether the sphere is visible in any camera.
  20093. */
  20094. intersectsSphere( sphere, cameraArray ) {
  20095. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20096. return false;
  20097. }
  20098. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20099. const camera = cameraArray.cameras[ i ];
  20100. _projScreenMatrix$2.multiplyMatrices(
  20101. camera.projectionMatrix,
  20102. camera.matrixWorldInverse
  20103. );
  20104. _frustum$1.setFromProjectionMatrix(
  20105. _projScreenMatrix$2,
  20106. camera.coordinateSystem,
  20107. camera.reversedDepth
  20108. );
  20109. if ( _frustum$1.intersectsSphere( sphere ) ) {
  20110. return true; // Sphere is visible in at least one camera
  20111. }
  20112. }
  20113. return false; // Not visible in any camera
  20114. }
  20115. /**
  20116. * Returns `true` if the given bounding box is intersecting any frustum
  20117. * from the camera array.
  20118. *
  20119. * @param {Box3} box - The bounding box to test.
  20120. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20121. * @return {boolean} Whether the box is visible in any camera.
  20122. */
  20123. intersectsBox( box, cameraArray ) {
  20124. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20125. return false;
  20126. }
  20127. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20128. const camera = cameraArray.cameras[ i ];
  20129. _projScreenMatrix$2.multiplyMatrices(
  20130. camera.projectionMatrix,
  20131. camera.matrixWorldInverse
  20132. );
  20133. _frustum$1.setFromProjectionMatrix(
  20134. _projScreenMatrix$2,
  20135. camera.coordinateSystem,
  20136. camera.reversedDepth
  20137. );
  20138. if ( _frustum$1.intersectsBox( box ) ) {
  20139. return true; // Box is visible in at least one camera
  20140. }
  20141. }
  20142. return false; // Not visible in any camera
  20143. }
  20144. /**
  20145. * Returns `true` if the given point lies within any frustum
  20146. * from the camera array.
  20147. *
  20148. * @param {Vector3} point - The point to test.
  20149. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20150. * @return {boolean} Whether the point is visible in any camera.
  20151. */
  20152. containsPoint( point, cameraArray ) {
  20153. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20154. return false;
  20155. }
  20156. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20157. const camera = cameraArray.cameras[ i ];
  20158. _projScreenMatrix$2.multiplyMatrices(
  20159. camera.projectionMatrix,
  20160. camera.matrixWorldInverse
  20161. );
  20162. _frustum$1.setFromProjectionMatrix(
  20163. _projScreenMatrix$2,
  20164. camera.coordinateSystem,
  20165. camera.reversedDepth
  20166. );
  20167. if ( _frustum$1.containsPoint( point ) ) {
  20168. return true; // Point is visible in at least one camera
  20169. }
  20170. }
  20171. return false; // Not visible in any camera
  20172. }
  20173. /**
  20174. * Returns a new frustum array with copied values from this instance.
  20175. *
  20176. * @return {FrustumArray} A clone of this instance.
  20177. */
  20178. clone() {
  20179. return new FrustumArray();
  20180. }
  20181. }
  20182. function ascIdSort( a, b ) {
  20183. return a - b;
  20184. }
  20185. function sortOpaque( a, b ) {
  20186. return a.z - b.z;
  20187. }
  20188. function sortTransparent( a, b ) {
  20189. return b.z - a.z;
  20190. }
  20191. class MultiDrawRenderList {
  20192. constructor() {
  20193. this.index = 0;
  20194. this.pool = [];
  20195. this.list = [];
  20196. }
  20197. push( start, count, z, index ) {
  20198. const pool = this.pool;
  20199. const list = this.list;
  20200. if ( this.index >= pool.length ) {
  20201. pool.push( {
  20202. start: -1,
  20203. count: -1,
  20204. z: -1,
  20205. index: -1,
  20206. } );
  20207. }
  20208. const item = pool[ this.index ];
  20209. list.push( item );
  20210. this.index ++;
  20211. item.start = start;
  20212. item.count = count;
  20213. item.z = z;
  20214. item.index = index;
  20215. }
  20216. reset() {
  20217. this.list.length = 0;
  20218. this.index = 0;
  20219. }
  20220. }
  20221. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20222. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20223. const _frustum = /*@__PURE__*/ new Frustum();
  20224. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20225. const _box$1 = /*@__PURE__*/ new Box3();
  20226. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20227. const _vector$5 = /*@__PURE__*/ new Vector3();
  20228. const _forward$1 = /*@__PURE__*/ new Vector3();
  20229. const _temp = /*@__PURE__*/ new Vector3();
  20230. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20231. const _mesh = /*@__PURE__*/ new Mesh();
  20232. const _batchIntersects = [];
  20233. // copies data from attribute "src" into "target" starting at "targetOffset"
  20234. function copyAttributeData( src, target, targetOffset = 0 ) {
  20235. const itemSize = target.itemSize;
  20236. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20237. // use the component getters and setters if the array data cannot
  20238. // be copied directly
  20239. const vertexCount = src.count;
  20240. for ( let i = 0; i < vertexCount; i ++ ) {
  20241. for ( let c = 0; c < itemSize; c ++ ) {
  20242. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20243. }
  20244. }
  20245. } else {
  20246. // faster copy approach using typed array set function
  20247. target.array.set( src.array, targetOffset * itemSize );
  20248. }
  20249. target.needsUpdate = true;
  20250. }
  20251. // safely copies array contents to a potentially smaller array
  20252. function copyArrayContents( src, target ) {
  20253. if ( src.constructor !== target.constructor ) {
  20254. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20255. const len = Math.min( src.length, target.length );
  20256. for ( let i = 0; i < len; i ++ ) {
  20257. target[ i ] = src[ i ];
  20258. }
  20259. } else {
  20260. // if the arrays use the same data layout we can use a fast block copy
  20261. const len = Math.min( src.length, target.length );
  20262. target.set( new src.constructor( src.buffer, 0, len ) );
  20263. }
  20264. }
  20265. /**
  20266. * A special version of a mesh with multi draw batch rendering support. Use
  20267. * this class if you have to render a large number of objects with the same
  20268. * material but with different geometries or world transformations. The usage of
  20269. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20270. * rendering performance in your application.
  20271. *
  20272. * ```js
  20273. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20274. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20275. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20276. *
  20277. * // initialize and add geometries into the batched mesh
  20278. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20279. * const boxGeometryId = batchedMesh.addGeometry( box );
  20280. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20281. *
  20282. * // create instances of those geometries
  20283. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20284. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20285. *
  20286. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20287. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20288. *
  20289. * // position the geometries
  20290. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20291. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20292. *
  20293. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20294. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20295. *
  20296. * scene.add( batchedMesh );
  20297. * ```
  20298. *
  20299. * @augments Mesh
  20300. */
  20301. class BatchedMesh extends Mesh {
  20302. /**
  20303. * Constructs a new batched mesh.
  20304. *
  20305. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20306. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20307. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20308. * @param {Material|Array<Material>} [material] - The mesh material.
  20309. */
  20310. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20311. super( new BufferGeometry(), material );
  20312. /**
  20313. * This flag can be used for type testing.
  20314. *
  20315. * @type {boolean}
  20316. * @readonly
  20317. * @default true
  20318. */
  20319. this.isBatchedMesh = true;
  20320. /**
  20321. * When set ot `true`, the individual objects of a batch are frustum culled.
  20322. *
  20323. * @type {boolean}
  20324. * @default true
  20325. */
  20326. this.perObjectFrustumCulled = true;
  20327. /**
  20328. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20329. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20330. * rendered front to back.
  20331. *
  20332. * @type {boolean}
  20333. * @default true
  20334. */
  20335. this.sortObjects = true;
  20336. /**
  20337. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20338. *
  20339. * @type {?Box3}
  20340. * @default null
  20341. */
  20342. this.boundingBox = null;
  20343. /**
  20344. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20345. *
  20346. * @type {?Sphere}
  20347. * @default null
  20348. */
  20349. this.boundingSphere = null;
  20350. /**
  20351. * Takes a sort a function that is run before render. The function takes a list of instances to
  20352. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20353. * sort with.
  20354. *
  20355. * @type {?Function}
  20356. * @default null
  20357. */
  20358. this.customSort = null;
  20359. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20360. this._instanceInfo = [];
  20361. this._geometryInfo = [];
  20362. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20363. this._availableInstanceIds = [];
  20364. this._availableGeometryIds = [];
  20365. // used to track where the next point is that geometry should be inserted
  20366. this._nextIndexStart = 0;
  20367. this._nextVertexStart = 0;
  20368. this._geometryCount = 0;
  20369. // flags
  20370. this._visibilityChanged = true;
  20371. this._geometryInitialized = false;
  20372. // cached user options
  20373. this._maxInstanceCount = maxInstanceCount;
  20374. this._maxVertexCount = maxVertexCount;
  20375. this._maxIndexCount = maxIndexCount;
  20376. // buffers for multi draw
  20377. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20378. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20379. this._multiDrawCount = 0;
  20380. this._multiDrawInstances = null;
  20381. // Local matrix per geometry by using data texture
  20382. this._matricesTexture = null;
  20383. this._indirectTexture = null;
  20384. this._colorsTexture = null;
  20385. this._initMatricesTexture();
  20386. this._initIndirectTexture();
  20387. }
  20388. /**
  20389. * The maximum number of individual instances that can be stored in the batch.
  20390. *
  20391. * @type {number}
  20392. * @readonly
  20393. */
  20394. get maxInstanceCount() {
  20395. return this._maxInstanceCount;
  20396. }
  20397. /**
  20398. * The instance count.
  20399. *
  20400. * @type {number}
  20401. * @readonly
  20402. */
  20403. get instanceCount() {
  20404. return this._instanceInfo.length - this._availableInstanceIds.length;
  20405. }
  20406. /**
  20407. * The number of unused vertices.
  20408. *
  20409. * @type {number}
  20410. * @readonly
  20411. */
  20412. get unusedVertexCount() {
  20413. return this._maxVertexCount - this._nextVertexStart;
  20414. }
  20415. /**
  20416. * The number of unused indices.
  20417. *
  20418. * @type {number}
  20419. * @readonly
  20420. */
  20421. get unusedIndexCount() {
  20422. return this._maxIndexCount - this._nextIndexStart;
  20423. }
  20424. _initMatricesTexture() {
  20425. // layout (1 matrix = 4 pixels)
  20426. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20427. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20428. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20429. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20430. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20431. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20432. size = Math.ceil( size / 4 ) * 4;
  20433. size = Math.max( size, 4 );
  20434. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20435. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20436. this._matricesTexture = matricesTexture;
  20437. }
  20438. _initIndirectTexture() {
  20439. let size = Math.sqrt( this._maxInstanceCount );
  20440. size = Math.ceil( size );
  20441. const indirectArray = new Uint32Array( size * size );
  20442. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20443. this._indirectTexture = indirectTexture;
  20444. }
  20445. _initColorsTexture() {
  20446. let size = Math.sqrt( this._maxInstanceCount );
  20447. size = Math.ceil( size );
  20448. // 4 floats per RGBA pixel initialized to white
  20449. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20450. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20451. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20452. this._colorsTexture = colorsTexture;
  20453. }
  20454. _initializeGeometry( reference ) {
  20455. const geometry = this.geometry;
  20456. const maxVertexCount = this._maxVertexCount;
  20457. const maxIndexCount = this._maxIndexCount;
  20458. if ( this._geometryInitialized === false ) {
  20459. for ( const attributeName in reference.attributes ) {
  20460. const srcAttribute = reference.getAttribute( attributeName );
  20461. const { array, itemSize, normalized } = srcAttribute;
  20462. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20463. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20464. geometry.setAttribute( attributeName, dstAttribute );
  20465. }
  20466. if ( reference.getIndex() !== null ) {
  20467. // Reserve last u16 index for primitive restart.
  20468. const indexArray = maxVertexCount > 65535
  20469. ? new Uint32Array( maxIndexCount )
  20470. : new Uint16Array( maxIndexCount );
  20471. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20472. }
  20473. this._geometryInitialized = true;
  20474. }
  20475. }
  20476. // Make sure the geometry is compatible with the existing combined geometry attributes
  20477. _validateGeometry( geometry ) {
  20478. // check to ensure the geometries are using consistent attributes and indices
  20479. const batchGeometry = this.geometry;
  20480. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20481. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20482. }
  20483. for ( const attributeName in batchGeometry.attributes ) {
  20484. if ( ! geometry.hasAttribute( attributeName ) ) {
  20485. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20486. }
  20487. const srcAttribute = geometry.getAttribute( attributeName );
  20488. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20489. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20490. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20491. }
  20492. }
  20493. }
  20494. /**
  20495. * Validates the instance defined by the given ID.
  20496. *
  20497. * @param {number} instanceId - The instance to validate.
  20498. */
  20499. validateInstanceId( instanceId ) {
  20500. const instanceInfo = this._instanceInfo;
  20501. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20502. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20503. }
  20504. }
  20505. /**
  20506. * Validates the geometry defined by the given ID.
  20507. *
  20508. * @param {number} geometryId - The geometry to validate.
  20509. */
  20510. validateGeometryId( geometryId ) {
  20511. const geometryInfoList = this._geometryInfo;
  20512. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20513. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20514. }
  20515. }
  20516. /**
  20517. * Takes a sort a function that is run before render. The function takes a list of instances to
  20518. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20519. *
  20520. * @param {Function} func - The custom sort function.
  20521. * @return {BatchedMesh} A reference to this batched mesh.
  20522. */
  20523. setCustomSort( func ) {
  20524. this.customSort = func;
  20525. return this;
  20526. }
  20527. /**
  20528. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20529. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20530. * otherwise they are `null`.
  20531. */
  20532. computeBoundingBox() {
  20533. if ( this.boundingBox === null ) {
  20534. this.boundingBox = new Box3();
  20535. }
  20536. const boundingBox = this.boundingBox;
  20537. const instanceInfo = this._instanceInfo;
  20538. boundingBox.makeEmpty();
  20539. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20540. if ( instanceInfo[ i ].active === false ) continue;
  20541. const geometryId = instanceInfo[ i ].geometryIndex;
  20542. this.getMatrixAt( i, _matrix$1 );
  20543. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20544. boundingBox.union( _box$1 );
  20545. }
  20546. }
  20547. /**
  20548. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20549. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20550. * otherwise they are `null`.
  20551. */
  20552. computeBoundingSphere() {
  20553. if ( this.boundingSphere === null ) {
  20554. this.boundingSphere = new Sphere();
  20555. }
  20556. const boundingSphere = this.boundingSphere;
  20557. const instanceInfo = this._instanceInfo;
  20558. boundingSphere.makeEmpty();
  20559. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20560. if ( instanceInfo[ i ].active === false ) continue;
  20561. const geometryId = instanceInfo[ i ].geometryIndex;
  20562. this.getMatrixAt( i, _matrix$1 );
  20563. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20564. boundingSphere.union( _sphere$2 );
  20565. }
  20566. }
  20567. /**
  20568. * Adds a new instance to the batch using the geometry of the given ID and returns
  20569. * a new id referring to the new instance to be used by other functions.
  20570. *
  20571. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20572. * @return {number} The instance ID.
  20573. */
  20574. addInstance( geometryId ) {
  20575. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20576. // ensure we're not over geometry
  20577. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20578. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20579. }
  20580. const instanceInfo = {
  20581. visible: true,
  20582. active: true,
  20583. geometryIndex: geometryId,
  20584. };
  20585. let drawId = null;
  20586. // Prioritize using previously freed instance ids
  20587. if ( this._availableInstanceIds.length > 0 ) {
  20588. this._availableInstanceIds.sort( ascIdSort );
  20589. drawId = this._availableInstanceIds.shift();
  20590. this._instanceInfo[ drawId ] = instanceInfo;
  20591. } else {
  20592. drawId = this._instanceInfo.length;
  20593. this._instanceInfo.push( instanceInfo );
  20594. }
  20595. const matricesTexture = this._matricesTexture;
  20596. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20597. matricesTexture.needsUpdate = true;
  20598. const colorsTexture = this._colorsTexture;
  20599. if ( colorsTexture ) {
  20600. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20601. colorsTexture.needsUpdate = true;
  20602. }
  20603. this._visibilityChanged = true;
  20604. return drawId;
  20605. }
  20606. /**
  20607. * Adds the given geometry to the batch and returns the associated
  20608. * geometry id referring to it to be used in other functions.
  20609. *
  20610. * @param {BufferGeometry} geometry - The geometry to add.
  20611. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20612. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20613. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20614. * Defaults to the length of the given geometry vertex buffer.
  20615. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20616. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20617. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20618. * the length of the given geometry index buffer.
  20619. * @return {number} The geometry ID.
  20620. */
  20621. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20622. this._initializeGeometry( geometry );
  20623. this._validateGeometry( geometry );
  20624. const geometryInfo = {
  20625. // geometry information
  20626. vertexStart: -1,
  20627. vertexCount: -1,
  20628. reservedVertexCount: -1,
  20629. indexStart: -1,
  20630. indexCount: -1,
  20631. reservedIndexCount: -1,
  20632. // draw range information
  20633. start: -1,
  20634. count: -1,
  20635. // state
  20636. boundingBox: null,
  20637. boundingSphere: null,
  20638. active: true,
  20639. };
  20640. const geometryInfoList = this._geometryInfo;
  20641. geometryInfo.vertexStart = this._nextVertexStart;
  20642. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20643. const index = geometry.getIndex();
  20644. const hasIndex = index !== null;
  20645. if ( hasIndex ) {
  20646. geometryInfo.indexStart = this._nextIndexStart;
  20647. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20648. }
  20649. if (
  20650. geometryInfo.indexStart !== -1 &&
  20651. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20652. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20653. ) {
  20654. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20655. }
  20656. // update id
  20657. let geometryId;
  20658. if ( this._availableGeometryIds.length > 0 ) {
  20659. this._availableGeometryIds.sort( ascIdSort );
  20660. geometryId = this._availableGeometryIds.shift();
  20661. geometryInfoList[ geometryId ] = geometryInfo;
  20662. } else {
  20663. geometryId = this._geometryCount;
  20664. this._geometryCount ++;
  20665. geometryInfoList.push( geometryInfo );
  20666. }
  20667. // update the geometry
  20668. this.setGeometryAt( geometryId, geometry );
  20669. // increment the next geometry position
  20670. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20671. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20672. return geometryId;
  20673. }
  20674. /**
  20675. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20676. * is not enough space reserved for geometry. Calling this will change all instances that are
  20677. * rendering that geometry.
  20678. *
  20679. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20680. * @param {BufferGeometry} geometry - The new geometry.
  20681. * @return {number} The geometry ID.
  20682. */
  20683. setGeometryAt( geometryId, geometry ) {
  20684. if ( geometryId >= this._geometryCount ) {
  20685. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20686. }
  20687. this._validateGeometry( geometry );
  20688. const batchGeometry = this.geometry;
  20689. const hasIndex = batchGeometry.getIndex() !== null;
  20690. const dstIndex = batchGeometry.getIndex();
  20691. const srcIndex = geometry.getIndex();
  20692. const geometryInfo = this._geometryInfo[ geometryId ];
  20693. if (
  20694. hasIndex &&
  20695. srcIndex.count > geometryInfo.reservedIndexCount ||
  20696. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20697. ) {
  20698. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20699. }
  20700. // copy geometry buffer data over
  20701. const vertexStart = geometryInfo.vertexStart;
  20702. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20703. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20704. for ( const attributeName in batchGeometry.attributes ) {
  20705. // copy attribute data
  20706. const srcAttribute = geometry.getAttribute( attributeName );
  20707. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20708. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20709. // fill the rest in with zeroes
  20710. const itemSize = srcAttribute.itemSize;
  20711. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20712. const index = vertexStart + i;
  20713. for ( let c = 0; c < itemSize; c ++ ) {
  20714. dstAttribute.setComponent( index, c, 0 );
  20715. }
  20716. }
  20717. dstAttribute.needsUpdate = true;
  20718. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20719. }
  20720. // copy index
  20721. if ( hasIndex ) {
  20722. const indexStart = geometryInfo.indexStart;
  20723. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20724. geometryInfo.indexCount = geometry.getIndex().count;
  20725. // copy index data over
  20726. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20727. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20728. }
  20729. // fill the rest in with zeroes
  20730. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20731. dstIndex.setX( indexStart + i, vertexStart );
  20732. }
  20733. dstIndex.needsUpdate = true;
  20734. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20735. }
  20736. // update the draw range
  20737. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20738. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20739. // store the bounding boxes
  20740. geometryInfo.boundingBox = null;
  20741. if ( geometry.boundingBox !== null ) {
  20742. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20743. }
  20744. geometryInfo.boundingSphere = null;
  20745. if ( geometry.boundingSphere !== null ) {
  20746. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20747. }
  20748. this._visibilityChanged = true;
  20749. return geometryId;
  20750. }
  20751. /**
  20752. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20753. * this geometry will also be removed as a side effect.
  20754. *
  20755. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20756. * @return {BatchedMesh} A reference to this batched mesh.
  20757. */
  20758. deleteGeometry( geometryId ) {
  20759. const geometryInfoList = this._geometryInfo;
  20760. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20761. return this;
  20762. }
  20763. // delete any instances associated with this geometry
  20764. const instanceInfo = this._instanceInfo;
  20765. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20766. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20767. this.deleteInstance( i );
  20768. }
  20769. }
  20770. geometryInfoList[ geometryId ].active = false;
  20771. this._availableGeometryIds.push( geometryId );
  20772. this._visibilityChanged = true;
  20773. return this;
  20774. }
  20775. /**
  20776. * Deletes an existing instance from the batch using the given ID.
  20777. *
  20778. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20779. * @return {BatchedMesh} A reference to this batched mesh.
  20780. */
  20781. deleteInstance( instanceId ) {
  20782. this.validateInstanceId( instanceId );
  20783. this._instanceInfo[ instanceId ].active = false;
  20784. this._availableInstanceIds.push( instanceId );
  20785. this._visibilityChanged = true;
  20786. return this;
  20787. }
  20788. /**
  20789. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20790. * previously deleted geometry, freeing up space to add new geometry.
  20791. *
  20792. * @return {BatchedMesh} A reference to this batched mesh.
  20793. */
  20794. optimize() {
  20795. // track the next indices to copy data to
  20796. let nextVertexStart = 0;
  20797. let nextIndexStart = 0;
  20798. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20799. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20800. const geometryInfoList = this._geometryInfo;
  20801. const indices = geometryInfoList
  20802. .map( ( e, i ) => i )
  20803. .sort( ( a, b ) => {
  20804. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20805. } );
  20806. const geometry = this.geometry;
  20807. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20808. // if a geometry range is inactive then don't copy anything
  20809. const index = indices[ i ];
  20810. const geometryInfo = geometryInfoList[ index ];
  20811. if ( geometryInfo.active === false ) {
  20812. continue;
  20813. }
  20814. // if a geometry contains an index buffer then shift it, as well
  20815. if ( geometry.index !== null ) {
  20816. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20817. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20818. const index = geometry.index;
  20819. const array = index.array;
  20820. // shift the index pointers based on how the vertex data will shift
  20821. // adjusting the index must happen first so the original vertex start value is available
  20822. const elementDelta = nextVertexStart - vertexStart;
  20823. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20824. array[ j ] = array[ j ] + elementDelta;
  20825. }
  20826. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20827. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20828. index.needsUpdate = true;
  20829. geometryInfo.indexStart = nextIndexStart;
  20830. }
  20831. nextIndexStart += geometryInfo.reservedIndexCount;
  20832. }
  20833. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20834. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20835. const { vertexStart, reservedVertexCount } = geometryInfo;
  20836. const attributes = geometry.attributes;
  20837. for ( const key in attributes ) {
  20838. const attribute = attributes[ key ];
  20839. const { array, itemSize } = attribute;
  20840. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20841. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20842. attribute.needsUpdate = true;
  20843. }
  20844. geometryInfo.vertexStart = nextVertexStart;
  20845. }
  20846. nextVertexStart += geometryInfo.reservedVertexCount;
  20847. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20848. }
  20849. this._nextIndexStart = nextIndexStart;
  20850. this._nextVertexStart = nextVertexStart;
  20851. this._visibilityChanged = true;
  20852. return this;
  20853. }
  20854. /**
  20855. * Returns the bounding box for the given geometry.
  20856. *
  20857. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20858. * @param {Box3} target - The target object that is used to store the method's result.
  20859. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20860. */
  20861. getBoundingBoxAt( geometryId, target ) {
  20862. if ( geometryId >= this._geometryCount ) {
  20863. return null;
  20864. }
  20865. // compute bounding box
  20866. const geometry = this.geometry;
  20867. const geometryInfo = this._geometryInfo[ geometryId ];
  20868. if ( geometryInfo.boundingBox === null ) {
  20869. const box = new Box3();
  20870. const index = geometry.index;
  20871. const position = geometry.attributes.position;
  20872. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20873. let iv = i;
  20874. if ( index ) {
  20875. iv = index.getX( iv );
  20876. }
  20877. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20878. }
  20879. geometryInfo.boundingBox = box;
  20880. }
  20881. target.copy( geometryInfo.boundingBox );
  20882. return target;
  20883. }
  20884. /**
  20885. * Returns the bounding sphere for the given geometry.
  20886. *
  20887. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20888. * @param {Sphere} target - The target object that is used to store the method's result.
  20889. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20890. */
  20891. getBoundingSphereAt( geometryId, target ) {
  20892. if ( geometryId >= this._geometryCount ) {
  20893. return null;
  20894. }
  20895. // compute bounding sphere
  20896. const geometry = this.geometry;
  20897. const geometryInfo = this._geometryInfo[ geometryId ];
  20898. if ( geometryInfo.boundingSphere === null ) {
  20899. const sphere = new Sphere();
  20900. this.getBoundingBoxAt( geometryId, _box$1 );
  20901. _box$1.getCenter( sphere.center );
  20902. const index = geometry.index;
  20903. const position = geometry.attributes.position;
  20904. let maxRadiusSq = 0;
  20905. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20906. let iv = i;
  20907. if ( index ) {
  20908. iv = index.getX( iv );
  20909. }
  20910. _vector$5.fromBufferAttribute( position, iv );
  20911. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20912. }
  20913. sphere.radius = Math.sqrt( maxRadiusSq );
  20914. geometryInfo.boundingSphere = sphere;
  20915. }
  20916. target.copy( geometryInfo.boundingSphere );
  20917. return target;
  20918. }
  20919. /**
  20920. * Sets the given local transformation matrix to the defined instance.
  20921. * Negatively scaled matrices are not supported.
  20922. *
  20923. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20924. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20925. * @return {BatchedMesh} A reference to this batched mesh.
  20926. */
  20927. setMatrixAt( instanceId, matrix ) {
  20928. this.validateInstanceId( instanceId );
  20929. const matricesTexture = this._matricesTexture;
  20930. const matricesArray = this._matricesTexture.image.data;
  20931. matrix.toArray( matricesArray, instanceId * 16 );
  20932. matricesTexture.needsUpdate = true;
  20933. return this;
  20934. }
  20935. /**
  20936. * Returns the local transformation matrix of the defined instance.
  20937. *
  20938. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20939. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20940. * @return {Matrix4} The instance's local transformation matrix.
  20941. */
  20942. getMatrixAt( instanceId, matrix ) {
  20943. this.validateInstanceId( instanceId );
  20944. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20945. }
  20946. /**
  20947. * Sets the given color to the defined instance.
  20948. *
  20949. * @param {number} instanceId - The ID of an instance to set the color of.
  20950. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  20951. * @return {BatchedMesh} A reference to this batched mesh.
  20952. */
  20953. setColorAt( instanceId, color ) {
  20954. this.validateInstanceId( instanceId );
  20955. if ( this._colorsTexture === null ) {
  20956. this._initColorsTexture();
  20957. }
  20958. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20959. this._colorsTexture.needsUpdate = true;
  20960. return this;
  20961. }
  20962. /**
  20963. * Returns the color of the defined instance.
  20964. *
  20965. * @param {number} instanceId - The ID of an instance to get the color of.
  20966. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  20967. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  20968. */
  20969. getColorAt( instanceId, color ) {
  20970. this.validateInstanceId( instanceId );
  20971. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20972. }
  20973. /**
  20974. * Sets the visibility of the instance.
  20975. *
  20976. * @param {number} instanceId - The id of the instance to set the visibility of.
  20977. * @param {boolean} visible - Whether the instance is visible or not.
  20978. * @return {BatchedMesh} A reference to this batched mesh.
  20979. */
  20980. setVisibleAt( instanceId, visible ) {
  20981. this.validateInstanceId( instanceId );
  20982. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20983. return this;
  20984. }
  20985. this._instanceInfo[ instanceId ].visible = visible;
  20986. this._visibilityChanged = true;
  20987. return this;
  20988. }
  20989. /**
  20990. * Returns the visibility state of the defined instance.
  20991. *
  20992. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20993. * @return {boolean} Whether the instance is visible or not.
  20994. */
  20995. getVisibleAt( instanceId ) {
  20996. this.validateInstanceId( instanceId );
  20997. return this._instanceInfo[ instanceId ].visible;
  20998. }
  20999. /**
  21000. * Sets the geometry ID of the instance at the given index.
  21001. *
  21002. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  21003. * @param {number} geometryId - The geometry ID to be use by the instance.
  21004. * @return {BatchedMesh} A reference to this batched mesh.
  21005. */
  21006. setGeometryIdAt( instanceId, geometryId ) {
  21007. this.validateInstanceId( instanceId );
  21008. this.validateGeometryId( geometryId );
  21009. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  21010. return this;
  21011. }
  21012. /**
  21013. * Returns the geometry ID of the defined instance.
  21014. *
  21015. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  21016. * @return {number} The instance's geometry ID.
  21017. */
  21018. getGeometryIdAt( instanceId ) {
  21019. this.validateInstanceId( instanceId );
  21020. return this._instanceInfo[ instanceId ].geometryIndex;
  21021. }
  21022. /**
  21023. * Get the range representing the subset of triangles related to the attached geometry,
  21024. * indicating the starting offset and count, or `null` if invalid.
  21025. *
  21026. * @param {number} geometryId - The id of the geometry to get the range of.
  21027. * @param {Object} [target] - The target object that is used to store the method's result.
  21028. * @return {{
  21029. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  21030. * indexStart:number,indexCount:number,reservedIndexCount:number,
  21031. * start:number,count:number
  21032. * }} The result object with range data.
  21033. */
  21034. getGeometryRangeAt( geometryId, target = {} ) {
  21035. this.validateGeometryId( geometryId );
  21036. const geometryInfo = this._geometryInfo[ geometryId ];
  21037. target.vertexStart = geometryInfo.vertexStart;
  21038. target.vertexCount = geometryInfo.vertexCount;
  21039. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  21040. target.indexStart = geometryInfo.indexStart;
  21041. target.indexCount = geometryInfo.indexCount;
  21042. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  21043. target.start = geometryInfo.start;
  21044. target.count = geometryInfo.count;
  21045. return target;
  21046. }
  21047. /**
  21048. * Resizes the necessary buffers to support the provided number of instances.
  21049. * If the provided arguments shrink the number of instances but there are not enough
  21050. * unused Ids at the end of the list then an error is thrown.
  21051. *
  21052. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  21053. */
  21054. setInstanceCount( maxInstanceCount ) {
  21055. // shrink the available instances as much as possible
  21056. const availableInstanceIds = this._availableInstanceIds;
  21057. const instanceInfo = this._instanceInfo;
  21058. availableInstanceIds.sort( ascIdSort );
  21059. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  21060. instanceInfo.pop();
  21061. availableInstanceIds.pop();
  21062. }
  21063. // throw an error if it can't be shrunk to the desired size
  21064. if ( maxInstanceCount < instanceInfo.length ) {
  21065. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  21066. }
  21067. // copy the multi draw counts
  21068. const multiDrawCounts = new Int32Array( maxInstanceCount );
  21069. const multiDrawStarts = new Int32Array( maxInstanceCount );
  21070. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  21071. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  21072. this._multiDrawCounts = multiDrawCounts;
  21073. this._multiDrawStarts = multiDrawStarts;
  21074. this._maxInstanceCount = maxInstanceCount;
  21075. // update texture data for instance sampling
  21076. const indirectTexture = this._indirectTexture;
  21077. const matricesTexture = this._matricesTexture;
  21078. const colorsTexture = this._colorsTexture;
  21079. indirectTexture.dispose();
  21080. this._initIndirectTexture();
  21081. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  21082. matricesTexture.dispose();
  21083. this._initMatricesTexture();
  21084. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  21085. if ( colorsTexture ) {
  21086. colorsTexture.dispose();
  21087. this._initColorsTexture();
  21088. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  21089. }
  21090. }
  21091. /**
  21092. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  21093. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  21094. * end of the geometry attributes then an error is thrown.
  21095. *
  21096. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  21097. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  21098. */
  21099. setGeometrySize( maxVertexCount, maxIndexCount ) {
  21100. // Check if we can shrink to the requested vertex attribute size
  21101. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  21102. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  21103. if ( requiredVertexLength > maxVertexCount ) {
  21104. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21105. }
  21106. // Check if we can shrink to the requested index attribute size
  21107. if ( this.geometry.index ) {
  21108. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  21109. if ( requiredIndexLength > maxIndexCount ) {
  21110. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21111. }
  21112. }
  21113. //
  21114. // dispose of the previous geometry
  21115. const oldGeometry = this.geometry;
  21116. oldGeometry.dispose();
  21117. // recreate the geometry needed based on the previous variant
  21118. this._maxVertexCount = maxVertexCount;
  21119. this._maxIndexCount = maxIndexCount;
  21120. if ( this._geometryInitialized ) {
  21121. this._geometryInitialized = false;
  21122. this.geometry = new BufferGeometry();
  21123. this._initializeGeometry( oldGeometry );
  21124. }
  21125. // copy data from the previous geometry
  21126. const geometry = this.geometry;
  21127. if ( oldGeometry.index ) {
  21128. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  21129. }
  21130. for ( const key in oldGeometry.attributes ) {
  21131. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  21132. }
  21133. }
  21134. raycast( raycaster, intersects ) {
  21135. const instanceInfo = this._instanceInfo;
  21136. const geometryInfoList = this._geometryInfo;
  21137. const matrixWorld = this.matrixWorld;
  21138. const batchGeometry = this.geometry;
  21139. // iterate over each geometry
  21140. _mesh.material = this.material;
  21141. _mesh.geometry.index = batchGeometry.index;
  21142. _mesh.geometry.attributes = batchGeometry.attributes;
  21143. if ( _mesh.geometry.boundingBox === null ) {
  21144. _mesh.geometry.boundingBox = new Box3();
  21145. }
  21146. if ( _mesh.geometry.boundingSphere === null ) {
  21147. _mesh.geometry.boundingSphere = new Sphere();
  21148. }
  21149. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21150. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  21151. continue;
  21152. }
  21153. const geometryId = instanceInfo[ i ].geometryIndex;
  21154. const geometryInfo = geometryInfoList[ geometryId ];
  21155. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  21156. // get the intersects
  21157. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  21158. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  21159. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  21160. _mesh.raycast( raycaster, _batchIntersects );
  21161. // add batch id to the intersects
  21162. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  21163. const intersect = _batchIntersects[ j ];
  21164. intersect.object = this;
  21165. intersect.batchId = i;
  21166. intersects.push( intersect );
  21167. }
  21168. _batchIntersects.length = 0;
  21169. }
  21170. _mesh.material = null;
  21171. _mesh.geometry.index = null;
  21172. _mesh.geometry.attributes = {};
  21173. _mesh.geometry.setDrawRange( 0, Infinity );
  21174. }
  21175. copy( source ) {
  21176. super.copy( source );
  21177. this.geometry = source.geometry.clone();
  21178. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  21179. this.sortObjects = source.sortObjects;
  21180. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  21181. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  21182. this._geometryInfo = source._geometryInfo.map( info => ( {
  21183. ...info,
  21184. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  21185. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  21186. } ) );
  21187. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  21188. this._availableInstanceIds = source._availableInstanceIds.slice();
  21189. this._availableGeometryIds = source._availableGeometryIds.slice();
  21190. this._nextIndexStart = source._nextIndexStart;
  21191. this._nextVertexStart = source._nextVertexStart;
  21192. this._geometryCount = source._geometryCount;
  21193. this._maxInstanceCount = source._maxInstanceCount;
  21194. this._maxVertexCount = source._maxVertexCount;
  21195. this._maxIndexCount = source._maxIndexCount;
  21196. this._geometryInitialized = source._geometryInitialized;
  21197. this._multiDrawCounts = source._multiDrawCounts.slice();
  21198. this._multiDrawStarts = source._multiDrawStarts.slice();
  21199. this._indirectTexture = source._indirectTexture.clone();
  21200. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  21201. this._matricesTexture = source._matricesTexture.clone();
  21202. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  21203. if ( this._colorsTexture !== null ) {
  21204. this._colorsTexture = source._colorsTexture.clone();
  21205. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  21206. }
  21207. return this;
  21208. }
  21209. /**
  21210. * Frees the GPU-related resources allocated by this instance. Call this
  21211. * method whenever this instance is no longer used in your app.
  21212. */
  21213. dispose() {
  21214. // Assuming the geometry is not shared with other meshes
  21215. this.geometry.dispose();
  21216. this._matricesTexture.dispose();
  21217. this._matricesTexture = null;
  21218. this._indirectTexture.dispose();
  21219. this._indirectTexture = null;
  21220. if ( this._colorsTexture !== null ) {
  21221. this._colorsTexture.dispose();
  21222. this._colorsTexture = null;
  21223. }
  21224. }
  21225. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21226. // if visibility has not changed and frustum culling and object sorting is not required
  21227. // then skip iterating over all items
  21228. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21229. return;
  21230. }
  21231. // the indexed version of the multi draw function requires specifying the start
  21232. // offset in bytes.
  21233. const index = geometry.getIndex();
  21234. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21235. const instanceInfo = this._instanceInfo;
  21236. const multiDrawStarts = this._multiDrawStarts;
  21237. const multiDrawCounts = this._multiDrawCounts;
  21238. const geometryInfoList = this._geometryInfo;
  21239. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21240. const indirectTexture = this._indirectTexture;
  21241. const indirectArray = indirectTexture.image.data;
  21242. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21243. // prepare the frustum in the local frame
  21244. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21245. _matrix$1
  21246. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21247. .multiply( this.matrixWorld );
  21248. _frustum.setFromProjectionMatrix(
  21249. _matrix$1,
  21250. camera.coordinateSystem,
  21251. camera.reversedDepth
  21252. );
  21253. }
  21254. let multiDrawCount = 0;
  21255. if ( this.sortObjects ) {
  21256. // get the camera position in the local frame
  21257. _matrix$1.copy( this.matrixWorld ).invert();
  21258. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21259. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21260. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21261. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21262. const geometryId = instanceInfo[ i ].geometryIndex;
  21263. // get the bounds in world space
  21264. this.getMatrixAt( i, _matrix$1 );
  21265. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21266. // determine whether the batched geometry is within the frustum
  21267. let culled = false;
  21268. if ( perObjectFrustumCulled ) {
  21269. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21270. }
  21271. if ( ! culled ) {
  21272. // get the distance from camera used for sorting
  21273. const geometryInfo = geometryInfoList[ geometryId ];
  21274. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21275. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21276. }
  21277. }
  21278. }
  21279. // Sort the draw ranges and prep for rendering
  21280. const list = _renderList.list;
  21281. const customSort = this.customSort;
  21282. if ( customSort === null ) {
  21283. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21284. } else {
  21285. customSort.call( this, list, camera );
  21286. }
  21287. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21288. const item = list[ i ];
  21289. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21290. multiDrawCounts[ multiDrawCount ] = item.count;
  21291. indirectArray[ multiDrawCount ] = item.index;
  21292. multiDrawCount ++;
  21293. }
  21294. _renderList.reset();
  21295. } else {
  21296. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21297. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21298. const geometryId = instanceInfo[ i ].geometryIndex;
  21299. // determine whether the batched geometry is within the frustum
  21300. let culled = false;
  21301. if ( perObjectFrustumCulled ) {
  21302. // get the bounds in world space
  21303. this.getMatrixAt( i, _matrix$1 );
  21304. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21305. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21306. }
  21307. if ( ! culled ) {
  21308. const geometryInfo = geometryInfoList[ geometryId ];
  21309. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21310. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21311. indirectArray[ multiDrawCount ] = i;
  21312. multiDrawCount ++;
  21313. }
  21314. }
  21315. }
  21316. }
  21317. indirectTexture.needsUpdate = true;
  21318. this._multiDrawCount = multiDrawCount;
  21319. this._visibilityChanged = false;
  21320. }
  21321. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21322. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21323. }
  21324. }
  21325. /**
  21326. * A material for rendering line primitives.
  21327. *
  21328. * Materials define the appearance of renderable 3D objects.
  21329. *
  21330. * ```js
  21331. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21332. * ```
  21333. *
  21334. * @augments Material
  21335. */
  21336. class LineBasicMaterial extends Material {
  21337. /**
  21338. * Constructs a new line basic material.
  21339. *
  21340. * @param {Object} [parameters] - An object with one or more properties
  21341. * defining the material's appearance. Any property of the material
  21342. * (including any property from inherited materials) can be passed
  21343. * in here. Color values can be passed any type of value accepted
  21344. * by {@link Color#set}.
  21345. */
  21346. constructor( parameters ) {
  21347. super();
  21348. /**
  21349. * This flag can be used for type testing.
  21350. *
  21351. * @type {boolean}
  21352. * @readonly
  21353. * @default true
  21354. */
  21355. this.isLineBasicMaterial = true;
  21356. this.type = 'LineBasicMaterial';
  21357. /**
  21358. * Color of the material.
  21359. *
  21360. * @type {Color}
  21361. * @default (1,1,1)
  21362. */
  21363. this.color = new Color( 0xffffff );
  21364. /**
  21365. * Sets the color of the lines using data from a texture. The texture map
  21366. * color is modulated by the diffuse `color`.
  21367. *
  21368. * @type {?Texture}
  21369. * @default null
  21370. */
  21371. this.map = null;
  21372. /**
  21373. * Controls line thickness or lines.
  21374. *
  21375. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21376. * ignore this setting and always render line primitives with a
  21377. * width of one pixel.
  21378. *
  21379. * @type {number}
  21380. * @default 1
  21381. */
  21382. this.linewidth = 1;
  21383. /**
  21384. * Defines appearance of line ends.
  21385. *
  21386. * Can only be used with {@link SVGRenderer}.
  21387. *
  21388. * @type {('butt'|'round'|'square')}
  21389. * @default 'round'
  21390. */
  21391. this.linecap = 'round';
  21392. /**
  21393. * Defines appearance of line joints.
  21394. *
  21395. * Can only be used with {@link SVGRenderer}.
  21396. *
  21397. * @type {('round'|'bevel'|'miter')}
  21398. * @default 'round'
  21399. */
  21400. this.linejoin = 'round';
  21401. /**
  21402. * Whether the material is affected by fog or not.
  21403. *
  21404. * @type {boolean}
  21405. * @default true
  21406. */
  21407. this.fog = true;
  21408. this.setValues( parameters );
  21409. }
  21410. copy( source ) {
  21411. super.copy( source );
  21412. this.color.copy( source.color );
  21413. this.map = source.map;
  21414. this.linewidth = source.linewidth;
  21415. this.linecap = source.linecap;
  21416. this.linejoin = source.linejoin;
  21417. this.fog = source.fog;
  21418. return this;
  21419. }
  21420. }
  21421. const _vStart = /*@__PURE__*/ new Vector3();
  21422. const _vEnd = /*@__PURE__*/ new Vector3();
  21423. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21424. const _ray$1 = /*@__PURE__*/ new Ray();
  21425. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21426. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21427. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21428. /**
  21429. * A continuous line. The line are rendered by connecting consecutive
  21430. * vertices with straight lines.
  21431. *
  21432. * ```js
  21433. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21434. *
  21435. * const points = [];
  21436. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21437. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21438. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21439. *
  21440. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21441. *
  21442. * const line = new THREE.Line( geometry, material );
  21443. * scene.add( line );
  21444. * ```
  21445. *
  21446. * @augments Object3D
  21447. */
  21448. class Line extends Object3D {
  21449. /**
  21450. * Constructs a new line.
  21451. *
  21452. * @param {BufferGeometry} [geometry] - The line geometry.
  21453. * @param {Material|Array<Material>} [material] - The line material.
  21454. */
  21455. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21456. super();
  21457. /**
  21458. * This flag can be used for type testing.
  21459. *
  21460. * @type {boolean}
  21461. * @readonly
  21462. * @default true
  21463. */
  21464. this.isLine = true;
  21465. this.type = 'Line';
  21466. /**
  21467. * The line geometry.
  21468. *
  21469. * @type {BufferGeometry}
  21470. */
  21471. this.geometry = geometry;
  21472. /**
  21473. * The line material.
  21474. *
  21475. * @type {Material|Array<Material>}
  21476. * @default LineBasicMaterial
  21477. */
  21478. this.material = material;
  21479. /**
  21480. * A dictionary representing the morph targets in the geometry. The key is the
  21481. * morph targets name, the value its attribute index. This member is `undefined`
  21482. * by default and only set when morph targets are detected in the geometry.
  21483. *
  21484. * @type {Object<string,number>|undefined}
  21485. * @default undefined
  21486. */
  21487. this.morphTargetDictionary = undefined;
  21488. /**
  21489. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21490. * is applied. This member is `undefined` by default and only set when morph targets are
  21491. * detected in the geometry.
  21492. *
  21493. * @type {Array<number>|undefined}
  21494. * @default undefined
  21495. */
  21496. this.morphTargetInfluences = undefined;
  21497. this.updateMorphTargets();
  21498. }
  21499. copy( source, recursive ) {
  21500. super.copy( source, recursive );
  21501. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21502. this.geometry = source.geometry;
  21503. return this;
  21504. }
  21505. /**
  21506. * Computes an array of distance values which are necessary for rendering dashed lines.
  21507. * For each vertex in the geometry, the method calculates the cumulative length from the
  21508. * current point to the very beginning of the line.
  21509. *
  21510. * @return {Line} A reference to this line.
  21511. */
  21512. computeLineDistances() {
  21513. const geometry = this.geometry;
  21514. // we assume non-indexed geometry
  21515. if ( geometry.index === null ) {
  21516. const positionAttribute = geometry.attributes.position;
  21517. const lineDistances = [ 0 ];
  21518. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21519. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21520. _vEnd.fromBufferAttribute( positionAttribute, i );
  21521. lineDistances[ i ] = lineDistances[ i - 1 ];
  21522. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21523. }
  21524. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21525. } else {
  21526. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21527. }
  21528. return this;
  21529. }
  21530. /**
  21531. * Computes intersection points between a casted ray and this line.
  21532. *
  21533. * @param {Raycaster} raycaster - The raycaster.
  21534. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21535. */
  21536. raycast( raycaster, intersects ) {
  21537. const geometry = this.geometry;
  21538. const matrixWorld = this.matrixWorld;
  21539. const threshold = raycaster.params.Line.threshold;
  21540. const drawRange = geometry.drawRange;
  21541. // Checking boundingSphere distance to ray
  21542. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21543. _sphere$1.copy( geometry.boundingSphere );
  21544. _sphere$1.applyMatrix4( matrixWorld );
  21545. _sphere$1.radius += threshold;
  21546. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21547. //
  21548. _inverseMatrix$1.copy( matrixWorld ).invert();
  21549. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21550. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21551. const localThresholdSq = localThreshold * localThreshold;
  21552. const step = this.isLineSegments ? 2 : 1;
  21553. const index = geometry.index;
  21554. const attributes = geometry.attributes;
  21555. const positionAttribute = attributes.position;
  21556. if ( index !== null ) {
  21557. const start = Math.max( 0, drawRange.start );
  21558. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21559. for ( let i = start, l = end - 1; i < l; i += step ) {
  21560. const a = index.getX( i );
  21561. const b = index.getX( i + 1 );
  21562. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21563. if ( intersect ) {
  21564. intersects.push( intersect );
  21565. }
  21566. }
  21567. if ( this.isLineLoop ) {
  21568. const a = index.getX( end - 1 );
  21569. const b = index.getX( start );
  21570. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21571. if ( intersect ) {
  21572. intersects.push( intersect );
  21573. }
  21574. }
  21575. } else {
  21576. const start = Math.max( 0, drawRange.start );
  21577. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21578. for ( let i = start, l = end - 1; i < l; i += step ) {
  21579. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21580. if ( intersect ) {
  21581. intersects.push( intersect );
  21582. }
  21583. }
  21584. if ( this.isLineLoop ) {
  21585. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21586. if ( intersect ) {
  21587. intersects.push( intersect );
  21588. }
  21589. }
  21590. }
  21591. }
  21592. /**
  21593. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21594. * to make sure existing morph targets can influence this 3D object.
  21595. */
  21596. updateMorphTargets() {
  21597. const geometry = this.geometry;
  21598. const morphAttributes = geometry.morphAttributes;
  21599. const keys = Object.keys( morphAttributes );
  21600. if ( keys.length > 0 ) {
  21601. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21602. if ( morphAttribute !== undefined ) {
  21603. this.morphTargetInfluences = [];
  21604. this.morphTargetDictionary = {};
  21605. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21606. const name = morphAttribute[ m ].name || String( m );
  21607. this.morphTargetInfluences.push( 0 );
  21608. this.morphTargetDictionary[ name ] = m;
  21609. }
  21610. }
  21611. }
  21612. }
  21613. }
  21614. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21615. const positionAttribute = object.geometry.attributes.position;
  21616. _vStart.fromBufferAttribute( positionAttribute, a );
  21617. _vEnd.fromBufferAttribute( positionAttribute, b );
  21618. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21619. if ( distSq > thresholdSq ) return;
  21620. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21621. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21622. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21623. return {
  21624. distance: distance,
  21625. // What do we want? intersection point on the ray or on the segment??
  21626. // point: raycaster.ray.at( distance ),
  21627. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21628. index: i,
  21629. face: null,
  21630. faceIndex: null,
  21631. barycoord: null,
  21632. object: object
  21633. };
  21634. }
  21635. const _start = /*@__PURE__*/ new Vector3();
  21636. const _end = /*@__PURE__*/ new Vector3();
  21637. /**
  21638. * A series of lines drawn between pairs of vertices.
  21639. *
  21640. * @augments Line
  21641. */
  21642. class LineSegments extends Line {
  21643. /**
  21644. * Constructs a new line segments.
  21645. *
  21646. * @param {BufferGeometry} [geometry] - The line geometry.
  21647. * @param {Material|Array<Material>} [material] - The line material.
  21648. */
  21649. constructor( geometry, material ) {
  21650. super( geometry, material );
  21651. /**
  21652. * This flag can be used for type testing.
  21653. *
  21654. * @type {boolean}
  21655. * @readonly
  21656. * @default true
  21657. */
  21658. this.isLineSegments = true;
  21659. this.type = 'LineSegments';
  21660. }
  21661. computeLineDistances() {
  21662. const geometry = this.geometry;
  21663. // we assume non-indexed geometry
  21664. if ( geometry.index === null ) {
  21665. const positionAttribute = geometry.attributes.position;
  21666. const lineDistances = [];
  21667. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21668. _start.fromBufferAttribute( positionAttribute, i );
  21669. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21670. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21671. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21672. }
  21673. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21674. } else {
  21675. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21676. }
  21677. return this;
  21678. }
  21679. }
  21680. /**
  21681. * A continuous line. This is nearly the same as {@link Line} the only difference
  21682. * is that the last vertex is connected with the first vertex in order to close
  21683. * the line to form a loop.
  21684. *
  21685. * @augments Line
  21686. */
  21687. class LineLoop extends Line {
  21688. /**
  21689. * Constructs a new line loop.
  21690. *
  21691. * @param {BufferGeometry} [geometry] - The line geometry.
  21692. * @param {Material|Array<Material>} [material] - The line material.
  21693. */
  21694. constructor( geometry, material ) {
  21695. super( geometry, material );
  21696. /**
  21697. * This flag can be used for type testing.
  21698. *
  21699. * @type {boolean}
  21700. * @readonly
  21701. * @default true
  21702. */
  21703. this.isLineLoop = true;
  21704. this.type = 'LineLoop';
  21705. }
  21706. }
  21707. /**
  21708. * A material for rendering point primitives.
  21709. *
  21710. * Materials define the appearance of renderable 3D objects.
  21711. *
  21712. * ```js
  21713. * const vertices = [];
  21714. *
  21715. * for ( let i = 0; i < 10000; i ++ ) {
  21716. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21717. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21718. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21719. *
  21720. * vertices.push( x, y, z );
  21721. * }
  21722. *
  21723. * const geometry = new THREE.BufferGeometry();
  21724. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21725. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21726. * const points = new THREE.Points( geometry, material );
  21727. * scene.add( points );
  21728. * ```
  21729. *
  21730. * @augments Material
  21731. */
  21732. class PointsMaterial extends Material {
  21733. /**
  21734. * Constructs a new points material.
  21735. *
  21736. * @param {Object} [parameters] - An object with one or more properties
  21737. * defining the material's appearance. Any property of the material
  21738. * (including any property from inherited materials) can be passed
  21739. * in here. Color values can be passed any type of value accepted
  21740. * by {@link Color#set}.
  21741. */
  21742. constructor( parameters ) {
  21743. super();
  21744. /**
  21745. * This flag can be used for type testing.
  21746. *
  21747. * @type {boolean}
  21748. * @readonly
  21749. * @default true
  21750. */
  21751. this.isPointsMaterial = true;
  21752. this.type = 'PointsMaterial';
  21753. /**
  21754. * Color of the material.
  21755. *
  21756. * @type {Color}
  21757. * @default (1,1,1)
  21758. */
  21759. this.color = new Color( 0xffffff );
  21760. /**
  21761. * The color map. May optionally include an alpha channel, typically combined
  21762. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21763. * color is modulated by the diffuse `color`.
  21764. *
  21765. * @type {?Texture}
  21766. * @default null
  21767. */
  21768. this.map = null;
  21769. /**
  21770. * The alpha map is a grayscale texture that controls the opacity across the
  21771. * surface (black: fully transparent; white: fully opaque).
  21772. *
  21773. * Only the color of the texture is used, ignoring the alpha channel if one
  21774. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21775. * when sampling this texture due to the extra bit of precision provided for
  21776. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21777. * luminance/alpha textures will also still work as expected.
  21778. *
  21779. * @type {?Texture}
  21780. * @default null
  21781. */
  21782. this.alphaMap = null;
  21783. /**
  21784. * Defines the size of the points in pixels.
  21785. *
  21786. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete).
  21787. *
  21788. * @type {number}
  21789. * @default 1
  21790. */
  21791. this.size = 1;
  21792. /**
  21793. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21794. *
  21795. * @type {boolean}
  21796. * @default true
  21797. */
  21798. this.sizeAttenuation = true;
  21799. /**
  21800. * Whether the material is affected by fog or not.
  21801. *
  21802. * @type {boolean}
  21803. * @default true
  21804. */
  21805. this.fog = true;
  21806. this.setValues( parameters );
  21807. }
  21808. copy( source ) {
  21809. super.copy( source );
  21810. this.color.copy( source.color );
  21811. this.map = source.map;
  21812. this.alphaMap = source.alphaMap;
  21813. this.size = source.size;
  21814. this.sizeAttenuation = source.sizeAttenuation;
  21815. this.fog = source.fog;
  21816. return this;
  21817. }
  21818. }
  21819. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21820. const _ray = /*@__PURE__*/ new Ray();
  21821. const _sphere = /*@__PURE__*/ new Sphere();
  21822. const _position$2 = /*@__PURE__*/ new Vector3();
  21823. /**
  21824. * A class for displaying points or point clouds.
  21825. *
  21826. * @augments Object3D
  21827. */
  21828. class Points extends Object3D {
  21829. /**
  21830. * Constructs a new point cloud.
  21831. *
  21832. * @param {BufferGeometry} [geometry] - The points geometry.
  21833. * @param {Material|Array<Material>} [material] - The points material.
  21834. */
  21835. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21836. super();
  21837. /**
  21838. * This flag can be used for type testing.
  21839. *
  21840. * @type {boolean}
  21841. * @readonly
  21842. * @default true
  21843. */
  21844. this.isPoints = true;
  21845. this.type = 'Points';
  21846. /**
  21847. * The points geometry.
  21848. *
  21849. * @type {BufferGeometry}
  21850. */
  21851. this.geometry = geometry;
  21852. /**
  21853. * The line material.
  21854. *
  21855. * @type {Material|Array<Material>}
  21856. * @default PointsMaterial
  21857. */
  21858. this.material = material;
  21859. /**
  21860. * A dictionary representing the morph targets in the geometry. The key is the
  21861. * morph targets name, the value its attribute index. This member is `undefined`
  21862. * by default and only set when morph targets are detected in the geometry.
  21863. *
  21864. * @type {Object<string,number>|undefined}
  21865. * @default undefined
  21866. */
  21867. this.morphTargetDictionary = undefined;
  21868. /**
  21869. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21870. * is applied. This member is `undefined` by default and only set when morph targets are
  21871. * detected in the geometry.
  21872. *
  21873. * @type {Array<number>|undefined}
  21874. * @default undefined
  21875. */
  21876. this.morphTargetInfluences = undefined;
  21877. this.updateMorphTargets();
  21878. }
  21879. copy( source, recursive ) {
  21880. super.copy( source, recursive );
  21881. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21882. this.geometry = source.geometry;
  21883. return this;
  21884. }
  21885. /**
  21886. * Computes intersection points between a casted ray and this point cloud.
  21887. *
  21888. * @param {Raycaster} raycaster - The raycaster.
  21889. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21890. */
  21891. raycast( raycaster, intersects ) {
  21892. const geometry = this.geometry;
  21893. const matrixWorld = this.matrixWorld;
  21894. const threshold = raycaster.params.Points.threshold;
  21895. const drawRange = geometry.drawRange;
  21896. // Checking boundingSphere distance to ray
  21897. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21898. _sphere.copy( geometry.boundingSphere );
  21899. _sphere.applyMatrix4( matrixWorld );
  21900. _sphere.radius += threshold;
  21901. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21902. //
  21903. _inverseMatrix.copy( matrixWorld ).invert();
  21904. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21905. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21906. const localThresholdSq = localThreshold * localThreshold;
  21907. const index = geometry.index;
  21908. const attributes = geometry.attributes;
  21909. const positionAttribute = attributes.position;
  21910. if ( index !== null ) {
  21911. const start = Math.max( 0, drawRange.start );
  21912. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21913. for ( let i = start, il = end; i < il; i ++ ) {
  21914. const a = index.getX( i );
  21915. _position$2.fromBufferAttribute( positionAttribute, a );
  21916. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21917. }
  21918. } else {
  21919. const start = Math.max( 0, drawRange.start );
  21920. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21921. for ( let i = start, l = end; i < l; i ++ ) {
  21922. _position$2.fromBufferAttribute( positionAttribute, i );
  21923. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21924. }
  21925. }
  21926. }
  21927. /**
  21928. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21929. * to make sure existing morph targets can influence this 3D object.
  21930. */
  21931. updateMorphTargets() {
  21932. const geometry = this.geometry;
  21933. const morphAttributes = geometry.morphAttributes;
  21934. const keys = Object.keys( morphAttributes );
  21935. if ( keys.length > 0 ) {
  21936. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21937. if ( morphAttribute !== undefined ) {
  21938. this.morphTargetInfluences = [];
  21939. this.morphTargetDictionary = {};
  21940. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21941. const name = morphAttribute[ m ].name || String( m );
  21942. this.morphTargetInfluences.push( 0 );
  21943. this.morphTargetDictionary[ name ] = m;
  21944. }
  21945. }
  21946. }
  21947. }
  21948. }
  21949. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21950. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21951. if ( rayPointDistanceSq < localThresholdSq ) {
  21952. const intersectPoint = new Vector3();
  21953. _ray.closestPointToPoint( point, intersectPoint );
  21954. intersectPoint.applyMatrix4( matrixWorld );
  21955. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21956. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21957. intersects.push( {
  21958. distance: distance,
  21959. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21960. point: intersectPoint,
  21961. index: index,
  21962. face: null,
  21963. faceIndex: null,
  21964. barycoord: null,
  21965. object: object
  21966. } );
  21967. }
  21968. }
  21969. /**
  21970. * A texture for use with a video.
  21971. *
  21972. * ```js
  21973. * // assuming you have created a HTML video element with id="video"
  21974. * const video = document.getElementById( 'video' );
  21975. * const texture = new THREE.VideoTexture( video );
  21976. * ```
  21977. *
  21978. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21979. * set to THREE.SRGBColorSpace.
  21980. *
  21981. * Note: After the initial use of a texture, its dimensions, format, and type
  21982. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21983. *
  21984. * @augments Texture
  21985. */
  21986. class VideoTexture extends Texture {
  21987. /**
  21988. * Constructs a new video texture.
  21989. *
  21990. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21991. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21992. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21993. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21994. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21995. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21996. * @param {number} [format=RGBAFormat] - The texture format.
  21997. * @param {number} [type=UnsignedByteType] - The texture type.
  21998. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21999. */
  22000. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  22001. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22002. /**
  22003. * This flag can be used for type testing.
  22004. *
  22005. * @type {boolean}
  22006. * @readonly
  22007. * @default true
  22008. */
  22009. this.isVideoTexture = true;
  22010. /**
  22011. * Whether to generate mipmaps (if possible) for a texture.
  22012. *
  22013. * Overwritten and set to `false` by default.
  22014. *
  22015. * @type {boolean}
  22016. * @default false
  22017. */
  22018. this.generateMipmaps = false;
  22019. /**
  22020. * The video frame request callback identifier, which is a positive integer.
  22021. *
  22022. * Value of 0 represents no scheduled rVFC.
  22023. *
  22024. * @private
  22025. * @type {number}
  22026. */
  22027. this._requestVideoFrameCallbackId = 0;
  22028. const scope = this;
  22029. function updateVideo() {
  22030. scope.needsUpdate = true;
  22031. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  22032. }
  22033. if ( 'requestVideoFrameCallback' in video ) {
  22034. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  22035. }
  22036. }
  22037. clone() {
  22038. return new this.constructor( this.image ).copy( this );
  22039. }
  22040. /**
  22041. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  22042. * to `true` every time a new frame is available.
  22043. *
  22044. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  22045. */
  22046. update() {
  22047. const video = this.image;
  22048. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  22049. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  22050. this.needsUpdate = true;
  22051. }
  22052. }
  22053. dispose() {
  22054. if ( this._requestVideoFrameCallbackId !== 0 ) {
  22055. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  22056. this._requestVideoFrameCallbackId = 0;
  22057. }
  22058. super.dispose();
  22059. }
  22060. }
  22061. /**
  22062. * This class can be used as an alternative way to define video data. Instead of using
  22063. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  22064. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  22065. * video frames are decoded with the WebCodecs API.
  22066. *
  22067. * ```js
  22068. * const texture = new THREE.VideoFrameTexture();
  22069. * texture.setFrame( frame );
  22070. * ```
  22071. *
  22072. * @augments VideoTexture
  22073. */
  22074. class VideoFrameTexture extends VideoTexture {
  22075. /**
  22076. * Constructs a new video frame texture.
  22077. *
  22078. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22079. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22080. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22081. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22082. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22083. * @param {number} [format=RGBAFormat] - The texture format.
  22084. * @param {number} [type=UnsignedByteType] - The texture type.
  22085. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22086. */
  22087. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22088. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22089. /**
  22090. * This flag can be used for type testing.
  22091. *
  22092. * @type {boolean}
  22093. * @readonly
  22094. * @default true
  22095. */
  22096. this.isVideoFrameTexture = true;
  22097. }
  22098. /**
  22099. * This method overwritten with an empty implementation since
  22100. * this type of texture is updated via `setFrame()`.
  22101. */
  22102. update() {}
  22103. clone() {
  22104. return new this.constructor().copy( this ); // restoring Texture.clone()
  22105. }
  22106. /**
  22107. * Sets the current frame of the video. This will automatically update the texture
  22108. * so the data can be used for rendering.
  22109. *
  22110. * @param {VideoFrame} frame - The video frame.
  22111. */
  22112. setFrame( frame ) {
  22113. this.image = frame;
  22114. this.needsUpdate = true;
  22115. }
  22116. }
  22117. /**
  22118. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  22119. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  22120. * as a texture for further usage.
  22121. *
  22122. * ```js
  22123. * const pixelRatio = window.devicePixelRatio;
  22124. * const textureSize = 128 * pixelRatio;
  22125. *
  22126. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  22127. *
  22128. * // calculate start position for copying part of the frame data
  22129. * const vector = new Vector2();
  22130. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  22131. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  22132. *
  22133. * renderer.render( scene, camera );
  22134. *
  22135. * // copy part of the rendered frame into the framebuffer texture
  22136. * renderer.copyFramebufferToTexture( frameTexture, vector );
  22137. * ```
  22138. *
  22139. * @augments Texture
  22140. */
  22141. class FramebufferTexture extends Texture {
  22142. /**
  22143. * Constructs a new framebuffer texture.
  22144. *
  22145. * @param {number} [width] - The width of the texture.
  22146. * @param {number} [height] - The height of the texture.
  22147. */
  22148. constructor( width, height ) {
  22149. super( { width, height } );
  22150. /**
  22151. * This flag can be used for type testing.
  22152. *
  22153. * @type {boolean}
  22154. * @readonly
  22155. * @default true
  22156. */
  22157. this.isFramebufferTexture = true;
  22158. /**
  22159. * How the texture is sampled when a texel covers more than one pixel.
  22160. *
  22161. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22162. *
  22163. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22164. * @default NearestFilter
  22165. */
  22166. this.magFilter = NearestFilter;
  22167. /**
  22168. * How the texture is sampled when a texel covers less than one pixel.
  22169. *
  22170. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22171. *
  22172. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22173. * @default NearestFilter
  22174. */
  22175. this.minFilter = NearestFilter;
  22176. /**
  22177. * Whether to generate mipmaps (if possible) for a texture.
  22178. *
  22179. * Overwritten and set to `false` by default.
  22180. *
  22181. * @type {boolean}
  22182. * @default false
  22183. */
  22184. this.generateMipmaps = false;
  22185. this.needsUpdate = true;
  22186. }
  22187. }
  22188. /**
  22189. * Creates a texture based on data in compressed form.
  22190. *
  22191. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22192. *
  22193. * @augments Texture
  22194. */
  22195. class CompressedTexture extends Texture {
  22196. /**
  22197. * Constructs a new compressed texture.
  22198. *
  22199. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22200. * the data and dimensions.
  22201. * @param {number} width - The width of the texture.
  22202. * @param {number} height - The height of the texture.
  22203. * @param {number} [format=RGBAFormat] - The texture format.
  22204. * @param {number} [type=UnsignedByteType] - The texture type.
  22205. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22206. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22207. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22208. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22209. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22210. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22211. * @param {string} [colorSpace=NoColorSpace] - The color space.
  22212. */
  22213. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  22214. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  22215. /**
  22216. * This flag can be used for type testing.
  22217. *
  22218. * @type {boolean}
  22219. * @readonly
  22220. * @default true
  22221. */
  22222. this.isCompressedTexture = true;
  22223. /**
  22224. * The image property of a compressed texture just defines its dimensions.
  22225. *
  22226. * @type {{width:number,height:number}}
  22227. */
  22228. this.image = { width: width, height: height };
  22229. /**
  22230. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22231. *
  22232. * @type {Array<Object>}
  22233. */
  22234. this.mipmaps = mipmaps;
  22235. /**
  22236. * If set to `true`, the texture is flipped along the vertical axis when
  22237. * uploaded to the GPU.
  22238. *
  22239. * Overwritten and set to `false` by default since it is not possible to
  22240. * flip compressed textures.
  22241. *
  22242. * @type {boolean}
  22243. * @default false
  22244. * @readonly
  22245. */
  22246. this.flipY = false;
  22247. /**
  22248. * Whether to generate mipmaps (if possible) for a texture.
  22249. *
  22250. * Overwritten and set to `false` by default since it is not
  22251. * possible to generate mipmaps for compressed data. Mipmaps
  22252. * must be embedded in the compressed texture file.
  22253. *
  22254. * @type {boolean}
  22255. * @default false
  22256. * @readonly
  22257. */
  22258. this.generateMipmaps = false;
  22259. }
  22260. }
  22261. /**
  22262. * Creates a texture 2D array based on data in compressed form.
  22263. *
  22264. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22265. *
  22266. * @augments CompressedTexture
  22267. */
  22268. class CompressedArrayTexture extends CompressedTexture {
  22269. /**
  22270. * Constructs a new compressed array texture.
  22271. *
  22272. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22273. * the data and dimensions.
  22274. * @param {number} width - The width of the texture.
  22275. * @param {number} height - The height of the texture.
  22276. * @param {number} depth - The depth of the texture.
  22277. * @param {number} [format=RGBAFormat] - The min filter value.
  22278. * @param {number} [type=UnsignedByteType] - The min filter value.
  22279. */
  22280. constructor( mipmaps, width, height, depth, format, type ) {
  22281. super( mipmaps, width, height, format, type );
  22282. /**
  22283. * This flag can be used for type testing.
  22284. *
  22285. * @type {boolean}
  22286. * @readonly
  22287. * @default true
  22288. */
  22289. this.isCompressedArrayTexture = true;
  22290. /**
  22291. * The image property of a compressed texture just defines its dimensions.
  22292. *
  22293. * @name CompressedArrayTexture#image
  22294. * @type {{width:number,height:number,depth:number}}
  22295. */
  22296. this.image.depth = depth;
  22297. /**
  22298. * This defines how the texture is wrapped in the depth and corresponds to
  22299. * *W* in UVW mapping.
  22300. *
  22301. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22302. * @default ClampToEdgeWrapping
  22303. */
  22304. this.wrapR = ClampToEdgeWrapping;
  22305. /**
  22306. * A set of all layers which need to be updated in the texture.
  22307. *
  22308. * @type {Set<number>}
  22309. */
  22310. this.layerUpdates = new Set();
  22311. }
  22312. /**
  22313. * Describes that a specific layer of the texture needs to be updated.
  22314. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22315. * entire compressed texture array is sent to the GPU. Marking specific
  22316. * layers will only transmit subsets of all mipmaps associated with a
  22317. * specific depth in the array which is often much more performant.
  22318. *
  22319. * @param {number} layerIndex - The layer index that should be updated.
  22320. */
  22321. addLayerUpdate( layerIndex ) {
  22322. this.layerUpdates.add( layerIndex );
  22323. }
  22324. /**
  22325. * Resets the layer updates registry.
  22326. */
  22327. clearLayerUpdates() {
  22328. this.layerUpdates.clear();
  22329. }
  22330. }
  22331. /**
  22332. * Creates a cube texture based on data in compressed form.
  22333. *
  22334. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22335. *
  22336. * @augments CompressedTexture
  22337. */
  22338. class CompressedCubeTexture extends CompressedTexture {
  22339. /**
  22340. * Constructs a new compressed texture.
  22341. *
  22342. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22343. * @param {number} [format=RGBAFormat] - The texture format.
  22344. * @param {number} [type=UnsignedByteType] - The texture type.
  22345. */
  22346. constructor( images, format, type ) {
  22347. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22348. /**
  22349. * This flag can be used for type testing.
  22350. *
  22351. * @type {boolean}
  22352. * @readonly
  22353. * @default true
  22354. */
  22355. this.isCompressedCubeTexture = true;
  22356. /**
  22357. * This flag can be used for type testing.
  22358. *
  22359. * @type {boolean}
  22360. * @readonly
  22361. * @default true
  22362. */
  22363. this.isCubeTexture = true;
  22364. this.image = images;
  22365. }
  22366. }
  22367. /**
  22368. * Creates a texture from a canvas element.
  22369. *
  22370. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22371. * to `true` immediately since a canvas can directly be used for rendering.
  22372. *
  22373. * @augments Texture
  22374. */
  22375. class CanvasTexture extends Texture {
  22376. /**
  22377. * Constructs a new texture.
  22378. *
  22379. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22380. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22381. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22382. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22383. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22384. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22385. * @param {number} [format=RGBAFormat] - The texture format.
  22386. * @param {number} [type=UnsignedByteType] - The texture type.
  22387. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22388. */
  22389. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22390. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22391. /**
  22392. * This flag can be used for type testing.
  22393. *
  22394. * @type {boolean}
  22395. * @readonly
  22396. * @default true
  22397. */
  22398. this.isCanvasTexture = true;
  22399. this.needsUpdate = true;
  22400. }
  22401. }
  22402. /**
  22403. * This class can be used to automatically save the depth information of a
  22404. * rendering into a texture.
  22405. *
  22406. * @augments Texture
  22407. */
  22408. class DepthTexture extends Texture {
  22409. /**
  22410. * Constructs a new depth texture.
  22411. *
  22412. * @param {number} width - The width of the texture.
  22413. * @param {number} height - The height of the texture.
  22414. * @param {number} [type=UnsignedIntType] - The texture type.
  22415. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22416. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22417. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22418. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22419. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22420. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22421. * @param {number} [format=DepthFormat] - The texture format.
  22422. * @param {number} [depth=1] - The depth of the texture.
  22423. */
  22424. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22425. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22426. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22427. }
  22428. const image = { width: width, height: height, depth: depth };
  22429. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22430. /**
  22431. * This flag can be used for type testing.
  22432. *
  22433. * @type {boolean}
  22434. * @readonly
  22435. * @default true
  22436. */
  22437. this.isDepthTexture = true;
  22438. /**
  22439. * If set to `true`, the texture is flipped along the vertical axis when
  22440. * uploaded to the GPU.
  22441. *
  22442. * Overwritten and set to `false` by default.
  22443. *
  22444. * @type {boolean}
  22445. * @default false
  22446. */
  22447. this.flipY = false;
  22448. /**
  22449. * Whether to generate mipmaps (if possible) for a texture.
  22450. *
  22451. * Overwritten and set to `false` by default.
  22452. *
  22453. * @type {boolean}
  22454. * @default false
  22455. */
  22456. this.generateMipmaps = false;
  22457. /**
  22458. * Code corresponding to the depth compare function.
  22459. *
  22460. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22461. * @default null
  22462. */
  22463. this.compareFunction = null;
  22464. }
  22465. copy( source ) {
  22466. super.copy( source );
  22467. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22468. this.compareFunction = source.compareFunction;
  22469. return this;
  22470. }
  22471. toJSON( meta ) {
  22472. const data = super.toJSON( meta );
  22473. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22474. return data;
  22475. }
  22476. }
  22477. /**
  22478. * This class can be used to automatically save the depth information of a
  22479. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22480. *
  22481. * @augments DepthTexture
  22482. */
  22483. class CubeDepthTexture extends DepthTexture {
  22484. /**
  22485. * Constructs a new cube depth texture.
  22486. *
  22487. * @param {number} size - The size (width and height) of each cube face.
  22488. * @param {number} [type=UnsignedIntType] - The texture type.
  22489. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22490. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22491. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22492. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22493. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22494. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22495. * @param {number} [format=DepthFormat] - The texture format.
  22496. */
  22497. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22498. // Create 6 identical image descriptors for the cube faces
  22499. const image = { width: size, height: size, depth: 1 };
  22500. const images = [ image, image, image, image, image, image ];
  22501. // Call DepthTexture constructor with width, height
  22502. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22503. // Replace the single image with the array of 6 images
  22504. this.image = images;
  22505. /**
  22506. * This flag can be used for type testing.
  22507. *
  22508. * @type {boolean}
  22509. * @readonly
  22510. * @default true
  22511. */
  22512. this.isCubeDepthTexture = true;
  22513. /**
  22514. * Set to true for cube texture handling in WebGLTextures.
  22515. *
  22516. * @type {boolean}
  22517. * @readonly
  22518. * @default true
  22519. */
  22520. this.isCubeTexture = true;
  22521. }
  22522. /**
  22523. * Alias for {@link CubeDepthTexture#image}.
  22524. *
  22525. * @type {Array<Image>}
  22526. */
  22527. get images() {
  22528. return this.image;
  22529. }
  22530. set images( value ) {
  22531. this.image = value;
  22532. }
  22533. }
  22534. /**
  22535. * Represents a texture created externally with the same renderer context.
  22536. *
  22537. * This may be a texture from a protected media stream, device camera feed,
  22538. * or other data feeds like a depth sensor.
  22539. *
  22540. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22541. * the {@link WebGPURenderer} WebGPU backend.
  22542. *
  22543. * @augments Texture
  22544. */
  22545. class ExternalTexture extends Texture {
  22546. /**
  22547. * Creates a new raw texture.
  22548. *
  22549. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22550. */
  22551. constructor( sourceTexture = null ) {
  22552. super();
  22553. /**
  22554. * The external source texture.
  22555. *
  22556. * @type {?(WebGLTexture|GPUTexture)}
  22557. * @default null
  22558. */
  22559. this.sourceTexture = sourceTexture;
  22560. /**
  22561. * This flag can be used for type testing.
  22562. *
  22563. * @type {boolean}
  22564. * @readonly
  22565. * @default true
  22566. */
  22567. this.isExternalTexture = true;
  22568. }
  22569. copy( source ) {
  22570. super.copy( source );
  22571. this.sourceTexture = source.sourceTexture;
  22572. return this;
  22573. }
  22574. }
  22575. /**
  22576. * A geometry class for representing a capsule.
  22577. *
  22578. * ```js
  22579. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22580. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22581. * const capsule = new THREE.Mesh( geometry, material );
  22582. * scene.add( capsule );
  22583. * ```
  22584. *
  22585. * @augments BufferGeometry
  22586. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22587. */
  22588. class CapsuleGeometry extends BufferGeometry {
  22589. /**
  22590. * Constructs a new capsule geometry.
  22591. *
  22592. * @param {number} [radius=1] - Radius of the capsule.
  22593. * @param {number} [height=1] - Height of the middle section.
  22594. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22595. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22596. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22597. */
  22598. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22599. super();
  22600. this.type = 'CapsuleGeometry';
  22601. /**
  22602. * Holds the constructor parameters that have been
  22603. * used to generate the geometry. Any modification
  22604. * after instantiation does not change the geometry.
  22605. *
  22606. * @type {Object}
  22607. */
  22608. this.parameters = {
  22609. radius: radius,
  22610. height: height,
  22611. capSegments: capSegments,
  22612. radialSegments: radialSegments,
  22613. heightSegments: heightSegments,
  22614. };
  22615. height = Math.max( 0, height );
  22616. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22617. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22618. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22619. // buffers
  22620. const indices = [];
  22621. const vertices = [];
  22622. const normals = [];
  22623. const uvs = [];
  22624. // helper variables
  22625. const halfHeight = height / 2;
  22626. const capArcLength = ( Math.PI / 2 ) * radius;
  22627. const cylinderPartLength = height;
  22628. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22629. const numVerticalSegments = capSegments * 2 + heightSegments;
  22630. const verticesPerRow = radialSegments + 1;
  22631. const normal = new Vector3();
  22632. const vertex = new Vector3();
  22633. // generate vertices, normals, and uvs
  22634. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22635. let currentArcLength = 0;
  22636. let profileY = 0;
  22637. let profileRadius = 0;
  22638. let normalYComponent = 0;
  22639. if ( iy <= capSegments ) {
  22640. // bottom cap
  22641. const segmentProgress = iy / capSegments;
  22642. const angle = ( segmentProgress * Math.PI ) / 2;
  22643. profileY = - halfHeight - radius * Math.cos( angle );
  22644. profileRadius = radius * Math.sin( angle );
  22645. normalYComponent = - radius * Math.cos( angle );
  22646. currentArcLength = segmentProgress * capArcLength;
  22647. } else if ( iy <= capSegments + heightSegments ) {
  22648. // middle section
  22649. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22650. profileY = - halfHeight + segmentProgress * height;
  22651. profileRadius = radius;
  22652. normalYComponent = 0;
  22653. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22654. } else {
  22655. // top cap
  22656. const segmentProgress =
  22657. ( iy - capSegments - heightSegments ) / capSegments;
  22658. const angle = ( segmentProgress * Math.PI ) / 2;
  22659. profileY = halfHeight + radius * Math.sin( angle );
  22660. profileRadius = radius * Math.cos( angle );
  22661. normalYComponent = radius * Math.sin( angle );
  22662. currentArcLength =
  22663. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22664. }
  22665. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22666. // special case for the poles
  22667. let uOffset = 0;
  22668. if ( iy === 0 ) {
  22669. uOffset = 0.5 / radialSegments;
  22670. } else if ( iy === numVerticalSegments ) {
  22671. uOffset = -0.5 / radialSegments;
  22672. }
  22673. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22674. const u = ix / radialSegments;
  22675. const theta = u * Math.PI * 2;
  22676. const sinTheta = Math.sin( theta );
  22677. const cosTheta = Math.cos( theta );
  22678. // vertex
  22679. vertex.x = - profileRadius * cosTheta;
  22680. vertex.y = profileY;
  22681. vertex.z = profileRadius * sinTheta;
  22682. vertices.push( vertex.x, vertex.y, vertex.z );
  22683. // normal
  22684. normal.set(
  22685. - profileRadius * cosTheta,
  22686. normalYComponent,
  22687. profileRadius * sinTheta
  22688. );
  22689. normal.normalize();
  22690. normals.push( normal.x, normal.y, normal.z );
  22691. // uv
  22692. uvs.push( u + uOffset, v );
  22693. }
  22694. if ( iy > 0 ) {
  22695. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22696. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22697. const i1 = prevIndexRow + ix;
  22698. const i2 = prevIndexRow + ix + 1;
  22699. const i3 = iy * verticesPerRow + ix;
  22700. const i4 = iy * verticesPerRow + ix + 1;
  22701. indices.push( i1, i2, i3 );
  22702. indices.push( i2, i4, i3 );
  22703. }
  22704. }
  22705. }
  22706. // build geometry
  22707. this.setIndex( indices );
  22708. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22709. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22710. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22711. }
  22712. copy( source ) {
  22713. super.copy( source );
  22714. this.parameters = Object.assign( {}, source.parameters );
  22715. return this;
  22716. }
  22717. /**
  22718. * Factory method for creating an instance of this class from the given
  22719. * JSON object.
  22720. *
  22721. * @param {Object} data - A JSON object representing the serialized geometry.
  22722. * @return {CapsuleGeometry} A new instance.
  22723. */
  22724. static fromJSON( data ) {
  22725. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22726. }
  22727. }
  22728. /**
  22729. * A simple shape of Euclidean geometry. It is constructed from a
  22730. * number of triangular segments that are oriented around a central point and
  22731. * extend as far out as a given radius. It is built counter-clockwise from a
  22732. * start angle and a given central angle. It can also be used to create
  22733. * regular polygons, where the number of segments determines the number of
  22734. * sides.
  22735. *
  22736. * ```js
  22737. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22738. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22739. * const circle = new THREE.Mesh( geometry, material );
  22740. * scene.add( circle )
  22741. * ```
  22742. *
  22743. * @augments BufferGeometry
  22744. * @demo scenes/geometry-browser.html#CircleGeometry
  22745. */
  22746. class CircleGeometry extends BufferGeometry {
  22747. /**
  22748. * Constructs a new circle geometry.
  22749. *
  22750. * @param {number} [radius=1] - Radius of the circle.
  22751. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22752. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22753. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22754. * of the circular sector in radians. The default value results in a complete circle.
  22755. */
  22756. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22757. super();
  22758. this.type = 'CircleGeometry';
  22759. /**
  22760. * Holds the constructor parameters that have been
  22761. * used to generate the geometry. Any modification
  22762. * after instantiation does not change the geometry.
  22763. *
  22764. * @type {Object}
  22765. */
  22766. this.parameters = {
  22767. radius: radius,
  22768. segments: segments,
  22769. thetaStart: thetaStart,
  22770. thetaLength: thetaLength
  22771. };
  22772. segments = Math.max( 3, segments );
  22773. // buffers
  22774. const indices = [];
  22775. const vertices = [];
  22776. const normals = [];
  22777. const uvs = [];
  22778. // helper variables
  22779. const vertex = new Vector3();
  22780. const uv = new Vector2();
  22781. // center point
  22782. vertices.push( 0, 0, 0 );
  22783. normals.push( 0, 0, 1 );
  22784. uvs.push( 0.5, 0.5 );
  22785. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22786. const segment = thetaStart + s / segments * thetaLength;
  22787. // vertex
  22788. vertex.x = radius * Math.cos( segment );
  22789. vertex.y = radius * Math.sin( segment );
  22790. vertices.push( vertex.x, vertex.y, vertex.z );
  22791. // normal
  22792. normals.push( 0, 0, 1 );
  22793. // uvs
  22794. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22795. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22796. uvs.push( uv.x, uv.y );
  22797. }
  22798. // indices
  22799. for ( let i = 1; i <= segments; i ++ ) {
  22800. indices.push( i, i + 1, 0 );
  22801. }
  22802. // build geometry
  22803. this.setIndex( indices );
  22804. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22805. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22806. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22807. }
  22808. copy( source ) {
  22809. super.copy( source );
  22810. this.parameters = Object.assign( {}, source.parameters );
  22811. return this;
  22812. }
  22813. /**
  22814. * Factory method for creating an instance of this class from the given
  22815. * JSON object.
  22816. *
  22817. * @param {Object} data - A JSON object representing the serialized geometry.
  22818. * @return {CircleGeometry} A new instance.
  22819. */
  22820. static fromJSON( data ) {
  22821. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22822. }
  22823. }
  22824. /**
  22825. * A geometry class for representing a cylinder.
  22826. *
  22827. * ```js
  22828. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22829. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22830. * const cylinder = new THREE.Mesh( geometry, material );
  22831. * scene.add( cylinder );
  22832. * ```
  22833. *
  22834. * @augments BufferGeometry
  22835. * @demo scenes/geometry-browser.html#CylinderGeometry
  22836. */
  22837. class CylinderGeometry extends BufferGeometry {
  22838. /**
  22839. * Constructs a new cylinder geometry.
  22840. *
  22841. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22842. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22843. * @param {number} [height=1] - Height of the cylinder.
  22844. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22845. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22846. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22847. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22848. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22849. * The default value results in a complete cylinder.
  22850. */
  22851. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22852. super();
  22853. this.type = 'CylinderGeometry';
  22854. /**
  22855. * Holds the constructor parameters that have been
  22856. * used to generate the geometry. Any modification
  22857. * after instantiation does not change the geometry.
  22858. *
  22859. * @type {Object}
  22860. */
  22861. this.parameters = {
  22862. radiusTop: radiusTop,
  22863. radiusBottom: radiusBottom,
  22864. height: height,
  22865. radialSegments: radialSegments,
  22866. heightSegments: heightSegments,
  22867. openEnded: openEnded,
  22868. thetaStart: thetaStart,
  22869. thetaLength: thetaLength
  22870. };
  22871. const scope = this;
  22872. radialSegments = Math.floor( radialSegments );
  22873. heightSegments = Math.floor( heightSegments );
  22874. // buffers
  22875. const indices = [];
  22876. const vertices = [];
  22877. const normals = [];
  22878. const uvs = [];
  22879. // helper variables
  22880. let index = 0;
  22881. const indexArray = [];
  22882. const halfHeight = height / 2;
  22883. let groupStart = 0;
  22884. // generate geometry
  22885. generateTorso();
  22886. if ( openEnded === false ) {
  22887. if ( radiusTop > 0 ) generateCap( true );
  22888. if ( radiusBottom > 0 ) generateCap( false );
  22889. }
  22890. // build geometry
  22891. this.setIndex( indices );
  22892. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22893. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22894. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22895. function generateTorso() {
  22896. const normal = new Vector3();
  22897. const vertex = new Vector3();
  22898. let groupCount = 0;
  22899. // this will be used to calculate the normal
  22900. const slope = ( radiusBottom - radiusTop ) / height;
  22901. // generate vertices, normals and uvs
  22902. for ( let y = 0; y <= heightSegments; y ++ ) {
  22903. const indexRow = [];
  22904. const v = y / heightSegments;
  22905. // calculate the radius of the current row
  22906. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22907. for ( let x = 0; x <= radialSegments; x ++ ) {
  22908. const u = x / radialSegments;
  22909. const theta = u * thetaLength + thetaStart;
  22910. const sinTheta = Math.sin( theta );
  22911. const cosTheta = Math.cos( theta );
  22912. // vertex
  22913. vertex.x = radius * sinTheta;
  22914. vertex.y = - v * height + halfHeight;
  22915. vertex.z = radius * cosTheta;
  22916. vertices.push( vertex.x, vertex.y, vertex.z );
  22917. // normal
  22918. normal.set( sinTheta, slope, cosTheta ).normalize();
  22919. normals.push( normal.x, normal.y, normal.z );
  22920. // uv
  22921. uvs.push( u, 1 - v );
  22922. // save index of vertex in respective row
  22923. indexRow.push( index ++ );
  22924. }
  22925. // now save vertices of the row in our index array
  22926. indexArray.push( indexRow );
  22927. }
  22928. // generate indices
  22929. for ( let x = 0; x < radialSegments; x ++ ) {
  22930. for ( let y = 0; y < heightSegments; y ++ ) {
  22931. // we use the index array to access the correct indices
  22932. const a = indexArray[ y ][ x ];
  22933. const b = indexArray[ y + 1 ][ x ];
  22934. const c = indexArray[ y + 1 ][ x + 1 ];
  22935. const d = indexArray[ y ][ x + 1 ];
  22936. // faces
  22937. if ( radiusTop > 0 || y !== 0 ) {
  22938. indices.push( a, b, d );
  22939. groupCount += 3;
  22940. }
  22941. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22942. indices.push( b, c, d );
  22943. groupCount += 3;
  22944. }
  22945. }
  22946. }
  22947. // add a group to the geometry. this will ensure multi material support
  22948. scope.addGroup( groupStart, groupCount, 0 );
  22949. // calculate new start value for groups
  22950. groupStart += groupCount;
  22951. }
  22952. function generateCap( top ) {
  22953. // save the index of the first center vertex
  22954. const centerIndexStart = index;
  22955. const uv = new Vector2();
  22956. const vertex = new Vector3();
  22957. let groupCount = 0;
  22958. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22959. const sign = ( top === true ) ? 1 : -1;
  22960. // first we generate the center vertex data of the cap.
  22961. // because the geometry needs one set of uvs per face,
  22962. // we must generate a center vertex per face/segment
  22963. for ( let x = 1; x <= radialSegments; x ++ ) {
  22964. // vertex
  22965. vertices.push( 0, halfHeight * sign, 0 );
  22966. // normal
  22967. normals.push( 0, sign, 0 );
  22968. // uv
  22969. uvs.push( 0.5, 0.5 );
  22970. // increase index
  22971. index ++;
  22972. }
  22973. // save the index of the last center vertex
  22974. const centerIndexEnd = index;
  22975. // now we generate the surrounding vertices, normals and uvs
  22976. for ( let x = 0; x <= radialSegments; x ++ ) {
  22977. const u = x / radialSegments;
  22978. const theta = u * thetaLength + thetaStart;
  22979. const cosTheta = Math.cos( theta );
  22980. const sinTheta = Math.sin( theta );
  22981. // vertex
  22982. vertex.x = radius * sinTheta;
  22983. vertex.y = halfHeight * sign;
  22984. vertex.z = radius * cosTheta;
  22985. vertices.push( vertex.x, vertex.y, vertex.z );
  22986. // normal
  22987. normals.push( 0, sign, 0 );
  22988. // uv
  22989. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22990. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22991. uvs.push( uv.x, uv.y );
  22992. // increase index
  22993. index ++;
  22994. }
  22995. // generate indices
  22996. for ( let x = 0; x < radialSegments; x ++ ) {
  22997. const c = centerIndexStart + x;
  22998. const i = centerIndexEnd + x;
  22999. if ( top === true ) {
  23000. // face top
  23001. indices.push( i, i + 1, c );
  23002. } else {
  23003. // face bottom
  23004. indices.push( i + 1, i, c );
  23005. }
  23006. groupCount += 3;
  23007. }
  23008. // add a group to the geometry. this will ensure multi material support
  23009. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  23010. // calculate new start value for groups
  23011. groupStart += groupCount;
  23012. }
  23013. }
  23014. copy( source ) {
  23015. super.copy( source );
  23016. this.parameters = Object.assign( {}, source.parameters );
  23017. return this;
  23018. }
  23019. /**
  23020. * Factory method for creating an instance of this class from the given
  23021. * JSON object.
  23022. *
  23023. * @param {Object} data - A JSON object representing the serialized geometry.
  23024. * @return {CylinderGeometry} A new instance.
  23025. */
  23026. static fromJSON( data ) {
  23027. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  23028. }
  23029. }
  23030. /**
  23031. * A geometry class for representing a cone.
  23032. *
  23033. * ```js
  23034. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  23035. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23036. * const cone = new THREE.Mesh(geometry, material );
  23037. * scene.add( cone );
  23038. * ```
  23039. *
  23040. * @augments CylinderGeometry
  23041. * @demo scenes/geometry-browser.html#ConeGeometry
  23042. */
  23043. class ConeGeometry extends CylinderGeometry {
  23044. /**
  23045. * Constructs a new cone geometry.
  23046. *
  23047. * @param {number} [radius=1] - Radius of the cone base.
  23048. * @param {number} [height=1] - Height of the cone.
  23049. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  23050. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  23051. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  23052. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  23053. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  23054. * The default value results in a complete cone.
  23055. */
  23056. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23057. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23058. this.type = 'ConeGeometry';
  23059. /**
  23060. * Holds the constructor parameters that have been
  23061. * used to generate the geometry. Any modification
  23062. * after instantiation does not change the geometry.
  23063. *
  23064. * @type {Object}
  23065. */
  23066. this.parameters = {
  23067. radius: radius,
  23068. height: height,
  23069. radialSegments: radialSegments,
  23070. heightSegments: heightSegments,
  23071. openEnded: openEnded,
  23072. thetaStart: thetaStart,
  23073. thetaLength: thetaLength
  23074. };
  23075. }
  23076. /**
  23077. * Factory method for creating an instance of this class from the given
  23078. * JSON object.
  23079. *
  23080. * @param {Object} data - A JSON object representing the serialized geometry.
  23081. * @return {ConeGeometry} A new instance.
  23082. */
  23083. static fromJSON( data ) {
  23084. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  23085. }
  23086. }
  23087. /**
  23088. * A polyhedron is a solid in three dimensions with flat faces. This class
  23089. * will take an array of vertices, project them onto a sphere, and then
  23090. * divide them up to the desired level of detail.
  23091. *
  23092. * @augments BufferGeometry
  23093. */
  23094. class PolyhedronGeometry extends BufferGeometry {
  23095. /**
  23096. * Constructs a new polyhedron geometry.
  23097. *
  23098. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  23099. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  23100. * @param {number} [radius=1] - The radius of the shape.
  23101. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  23102. */
  23103. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  23104. super();
  23105. this.type = 'PolyhedronGeometry';
  23106. /**
  23107. * Holds the constructor parameters that have been
  23108. * used to generate the geometry. Any modification
  23109. * after instantiation does not change the geometry.
  23110. *
  23111. * @type {Object}
  23112. */
  23113. this.parameters = {
  23114. vertices: vertices,
  23115. indices: indices,
  23116. radius: radius,
  23117. detail: detail
  23118. };
  23119. // default buffer data
  23120. const vertexBuffer = [];
  23121. const uvBuffer = [];
  23122. // the subdivision creates the vertex buffer data
  23123. subdivide( detail );
  23124. // all vertices should lie on a conceptual sphere with a given radius
  23125. applyRadius( radius );
  23126. // finally, create the uv data
  23127. generateUVs();
  23128. // build non-indexed geometry
  23129. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  23130. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  23131. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  23132. if ( detail === 0 ) {
  23133. this.computeVertexNormals(); // flat normals
  23134. } else {
  23135. this.normalizeNormals(); // smooth normals
  23136. }
  23137. // helper functions
  23138. function subdivide( detail ) {
  23139. const a = new Vector3();
  23140. const b = new Vector3();
  23141. const c = new Vector3();
  23142. // iterate over all faces and apply a subdivision with the given detail value
  23143. for ( let i = 0; i < indices.length; i += 3 ) {
  23144. // get the vertices of the face
  23145. getVertexByIndex( indices[ i + 0 ], a );
  23146. getVertexByIndex( indices[ i + 1 ], b );
  23147. getVertexByIndex( indices[ i + 2 ], c );
  23148. // perform subdivision
  23149. subdivideFace( a, b, c, detail );
  23150. }
  23151. }
  23152. function subdivideFace( a, b, c, detail ) {
  23153. const cols = detail + 1;
  23154. // we use this multidimensional array as a data structure for creating the subdivision
  23155. const v = [];
  23156. // construct all of the vertices for this subdivision
  23157. for ( let i = 0; i <= cols; i ++ ) {
  23158. v[ i ] = [];
  23159. const aj = a.clone().lerp( c, i / cols );
  23160. const bj = b.clone().lerp( c, i / cols );
  23161. const rows = cols - i;
  23162. for ( let j = 0; j <= rows; j ++ ) {
  23163. if ( j === 0 && i === cols ) {
  23164. v[ i ][ j ] = aj;
  23165. } else {
  23166. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  23167. }
  23168. }
  23169. }
  23170. // construct all of the faces
  23171. for ( let i = 0; i < cols; i ++ ) {
  23172. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23173. const k = Math.floor( j / 2 );
  23174. if ( j % 2 === 0 ) {
  23175. pushVertex( v[ i ][ k + 1 ] );
  23176. pushVertex( v[ i + 1 ][ k ] );
  23177. pushVertex( v[ i ][ k ] );
  23178. } else {
  23179. pushVertex( v[ i ][ k + 1 ] );
  23180. pushVertex( v[ i + 1 ][ k + 1 ] );
  23181. pushVertex( v[ i + 1 ][ k ] );
  23182. }
  23183. }
  23184. }
  23185. }
  23186. function applyRadius( radius ) {
  23187. const vertex = new Vector3();
  23188. // iterate over the entire buffer and apply the radius to each vertex
  23189. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23190. vertex.x = vertexBuffer[ i + 0 ];
  23191. vertex.y = vertexBuffer[ i + 1 ];
  23192. vertex.z = vertexBuffer[ i + 2 ];
  23193. vertex.normalize().multiplyScalar( radius );
  23194. vertexBuffer[ i + 0 ] = vertex.x;
  23195. vertexBuffer[ i + 1 ] = vertex.y;
  23196. vertexBuffer[ i + 2 ] = vertex.z;
  23197. }
  23198. }
  23199. function generateUVs() {
  23200. const vertex = new Vector3();
  23201. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23202. vertex.x = vertexBuffer[ i + 0 ];
  23203. vertex.y = vertexBuffer[ i + 1 ];
  23204. vertex.z = vertexBuffer[ i + 2 ];
  23205. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  23206. const v = inclination( vertex ) / Math.PI + 0.5;
  23207. uvBuffer.push( u, 1 - v );
  23208. }
  23209. correctUVs();
  23210. correctSeam();
  23211. }
  23212. function correctSeam() {
  23213. // handle case when face straddles the seam, see #3269
  23214. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  23215. // uv data of a single face
  23216. const x0 = uvBuffer[ i + 0 ];
  23217. const x1 = uvBuffer[ i + 2 ];
  23218. const x2 = uvBuffer[ i + 4 ];
  23219. const max = Math.max( x0, x1, x2 );
  23220. const min = Math.min( x0, x1, x2 );
  23221. // 0.9 is somewhat arbitrary
  23222. if ( max > 0.9 && min < 0.1 ) {
  23223. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23224. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23225. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23226. }
  23227. }
  23228. }
  23229. function pushVertex( vertex ) {
  23230. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23231. }
  23232. function getVertexByIndex( index, vertex ) {
  23233. const stride = index * 3;
  23234. vertex.x = vertices[ stride + 0 ];
  23235. vertex.y = vertices[ stride + 1 ];
  23236. vertex.z = vertices[ stride + 2 ];
  23237. }
  23238. function correctUVs() {
  23239. const a = new Vector3();
  23240. const b = new Vector3();
  23241. const c = new Vector3();
  23242. const centroid = new Vector3();
  23243. const uvA = new Vector2();
  23244. const uvB = new Vector2();
  23245. const uvC = new Vector2();
  23246. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23247. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23248. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23249. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23250. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23251. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23252. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23253. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23254. const azi = azimuth( centroid );
  23255. correctUV( uvA, j + 0, a, azi );
  23256. correctUV( uvB, j + 2, b, azi );
  23257. correctUV( uvC, j + 4, c, azi );
  23258. }
  23259. }
  23260. function correctUV( uv, stride, vector, azimuth ) {
  23261. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23262. uvBuffer[ stride ] = uv.x - 1;
  23263. }
  23264. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23265. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23266. }
  23267. }
  23268. // Angle around the Y axis, counter-clockwise when looking from above.
  23269. function azimuth( vector ) {
  23270. return Math.atan2( vector.z, - vector.x );
  23271. }
  23272. // Angle above the XZ plane.
  23273. function inclination( vector ) {
  23274. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23275. }
  23276. }
  23277. copy( source ) {
  23278. super.copy( source );
  23279. this.parameters = Object.assign( {}, source.parameters );
  23280. return this;
  23281. }
  23282. /**
  23283. * Factory method for creating an instance of this class from the given
  23284. * JSON object.
  23285. *
  23286. * @param {Object} data - A JSON object representing the serialized geometry.
  23287. * @return {PolyhedronGeometry} A new instance.
  23288. */
  23289. static fromJSON( data ) {
  23290. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23291. }
  23292. }
  23293. /**
  23294. * A geometry class for representing a dodecahedron.
  23295. *
  23296. * ```js
  23297. * const geometry = new THREE.DodecahedronGeometry();
  23298. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23299. * const dodecahedron = new THREE.Mesh( geometry, material );
  23300. * scene.add( dodecahedron );
  23301. * ```
  23302. *
  23303. * @augments PolyhedronGeometry
  23304. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23305. */
  23306. class DodecahedronGeometry extends PolyhedronGeometry {
  23307. /**
  23308. * Constructs a new dodecahedron geometry.
  23309. *
  23310. * @param {number} [radius=1] - Radius of the dodecahedron.
  23311. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23312. */
  23313. constructor( radius = 1, detail = 0 ) {
  23314. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23315. const r = 1 / t;
  23316. const vertices = [
  23317. // (±1, ±1, ±1)
  23318. -1, -1, -1, -1, -1, 1,
  23319. -1, 1, -1, -1, 1, 1,
  23320. 1, -1, -1, 1, -1, 1,
  23321. 1, 1, -1, 1, 1, 1,
  23322. // (0, ±1/φ, ±φ)
  23323. 0, - r, - t, 0, - r, t,
  23324. 0, r, - t, 0, r, t,
  23325. // (±1/φ, ±φ, 0)
  23326. - r, - t, 0, - r, t, 0,
  23327. r, - t, 0, r, t, 0,
  23328. // (±φ, 0, ±1/φ)
  23329. - t, 0, - r, t, 0, - r,
  23330. - t, 0, r, t, 0, r
  23331. ];
  23332. const indices = [
  23333. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23334. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23335. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23336. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23337. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23338. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23339. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23340. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23341. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23342. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23343. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23344. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23345. ];
  23346. super( vertices, indices, radius, detail );
  23347. this.type = 'DodecahedronGeometry';
  23348. /**
  23349. * Holds the constructor parameters that have been
  23350. * used to generate the geometry. Any modification
  23351. * after instantiation does not change the geometry.
  23352. *
  23353. * @type {Object}
  23354. */
  23355. this.parameters = {
  23356. radius: radius,
  23357. detail: detail
  23358. };
  23359. }
  23360. /**
  23361. * Factory method for creating an instance of this class from the given
  23362. * JSON object.
  23363. *
  23364. * @param {Object} data - A JSON object representing the serialized geometry.
  23365. * @return {DodecahedronGeometry} A new instance.
  23366. */
  23367. static fromJSON( data ) {
  23368. return new DodecahedronGeometry( data.radius, data.detail );
  23369. }
  23370. }
  23371. const _v0$1 = /*@__PURE__*/ new Vector3();
  23372. const _v1$1 = /*@__PURE__*/ new Vector3();
  23373. const _normal = /*@__PURE__*/ new Vector3();
  23374. const _triangle = /*@__PURE__*/ new Triangle();
  23375. /**
  23376. * Can be used as a helper object to view the edges of a geometry.
  23377. *
  23378. * ```js
  23379. * const geometry = new THREE.BoxGeometry();
  23380. * const edges = new THREE.EdgesGeometry( geometry );
  23381. * const line = new THREE.LineSegments( edges );
  23382. * scene.add( line );
  23383. * ```
  23384. *
  23385. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23386. *
  23387. * @augments BufferGeometry
  23388. */
  23389. class EdgesGeometry extends BufferGeometry {
  23390. /**
  23391. * Constructs a new edges geometry.
  23392. *
  23393. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23394. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23395. * between the face normals of the adjoining faces exceeds this value.
  23396. */
  23397. constructor( geometry = null, thresholdAngle = 1 ) {
  23398. super();
  23399. this.type = 'EdgesGeometry';
  23400. /**
  23401. * Holds the constructor parameters that have been
  23402. * used to generate the geometry. Any modification
  23403. * after instantiation does not change the geometry.
  23404. *
  23405. * @type {Object}
  23406. */
  23407. this.parameters = {
  23408. geometry: geometry,
  23409. thresholdAngle: thresholdAngle
  23410. };
  23411. if ( geometry !== null ) {
  23412. const precisionPoints = 4;
  23413. const precision = Math.pow( 10, precisionPoints );
  23414. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23415. const indexAttr = geometry.getIndex();
  23416. const positionAttr = geometry.getAttribute( 'position' );
  23417. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23418. const indexArr = [ 0, 0, 0 ];
  23419. const vertKeys = [ 'a', 'b', 'c' ];
  23420. const hashes = new Array( 3 );
  23421. const edgeData = {};
  23422. const vertices = [];
  23423. for ( let i = 0; i < indexCount; i += 3 ) {
  23424. if ( indexAttr ) {
  23425. indexArr[ 0 ] = indexAttr.getX( i );
  23426. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23427. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23428. } else {
  23429. indexArr[ 0 ] = i;
  23430. indexArr[ 1 ] = i + 1;
  23431. indexArr[ 2 ] = i + 2;
  23432. }
  23433. const { a, b, c } = _triangle;
  23434. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23435. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23436. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23437. _triangle.getNormal( _normal );
  23438. // create hashes for the edge from the vertices
  23439. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23440. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23441. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23442. // skip degenerate triangles
  23443. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23444. continue;
  23445. }
  23446. // iterate over every edge
  23447. for ( let j = 0; j < 3; j ++ ) {
  23448. // get the first and next vertex making up the edge
  23449. const jNext = ( j + 1 ) % 3;
  23450. const vecHash0 = hashes[ j ];
  23451. const vecHash1 = hashes[ jNext ];
  23452. const v0 = _triangle[ vertKeys[ j ] ];
  23453. const v1 = _triangle[ vertKeys[ jNext ] ];
  23454. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23455. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23456. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23457. // if we found a sibling edge add it into the vertex array if
  23458. // it meets the angle threshold and delete the edge from the map.
  23459. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23460. vertices.push( v0.x, v0.y, v0.z );
  23461. vertices.push( v1.x, v1.y, v1.z );
  23462. }
  23463. edgeData[ reverseHash ] = null;
  23464. } else if ( ! ( hash in edgeData ) ) {
  23465. // if we've already got an edge here then skip adding a new one
  23466. edgeData[ hash ] = {
  23467. index0: indexArr[ j ],
  23468. index1: indexArr[ jNext ],
  23469. normal: _normal.clone(),
  23470. };
  23471. }
  23472. }
  23473. }
  23474. // iterate over all remaining, unmatched edges and add them to the vertex array
  23475. for ( const key in edgeData ) {
  23476. if ( edgeData[ key ] ) {
  23477. const { index0, index1 } = edgeData[ key ];
  23478. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23479. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23480. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23481. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23482. }
  23483. }
  23484. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23485. }
  23486. }
  23487. copy( source ) {
  23488. super.copy( source );
  23489. this.parameters = Object.assign( {}, source.parameters );
  23490. return this;
  23491. }
  23492. }
  23493. /**
  23494. * An abstract base class for creating an analytic curve object that contains methods
  23495. * for interpolation.
  23496. *
  23497. * @abstract
  23498. */
  23499. class Curve {
  23500. /**
  23501. * Constructs a new curve.
  23502. */
  23503. constructor() {
  23504. /**
  23505. * The type property is used for detecting the object type
  23506. * in context of serialization/deserialization.
  23507. *
  23508. * @type {string}
  23509. * @readonly
  23510. */
  23511. this.type = 'Curve';
  23512. /**
  23513. * This value determines the amount of divisions when calculating the
  23514. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23515. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23516. * recommended to increase the value of this property if the curve is very large.
  23517. *
  23518. * @type {number}
  23519. * @default 200
  23520. */
  23521. this.arcLengthDivisions = 200;
  23522. /**
  23523. * Must be set to `true` if the curve parameters have changed.
  23524. *
  23525. * @type {boolean}
  23526. * @default false
  23527. */
  23528. this.needsUpdate = false;
  23529. /**
  23530. * An internal cache that holds precomputed curve length values.
  23531. *
  23532. * @private
  23533. * @type {?Array<number>}
  23534. * @default null
  23535. */
  23536. this.cacheArcLengths = null;
  23537. }
  23538. /**
  23539. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23540. * for the given interpolation factor.
  23541. *
  23542. * @abstract
  23543. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23544. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23545. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23546. */
  23547. getPoint( /* t, optionalTarget */ ) {
  23548. warn( 'Curve: .getPoint() not implemented.' );
  23549. }
  23550. /**
  23551. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23552. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23553. * of the curve which equidistant samples.
  23554. *
  23555. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23556. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23557. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23558. */
  23559. getPointAt( u, optionalTarget ) {
  23560. const t = this.getUtoTmapping( u );
  23561. return this.getPoint( t, optionalTarget );
  23562. }
  23563. /**
  23564. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23565. * the curve shape.
  23566. *
  23567. * @param {number} [divisions=5] - The number of divisions.
  23568. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23569. */
  23570. getPoints( divisions = 5 ) {
  23571. const points = [];
  23572. for ( let d = 0; d <= divisions; d ++ ) {
  23573. points.push( this.getPoint( d / divisions ) );
  23574. }
  23575. return points;
  23576. }
  23577. // Get sequence of points using getPointAt( u )
  23578. /**
  23579. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23580. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23581. * curve.
  23582. *
  23583. * @param {number} [divisions=5] - The number of divisions.
  23584. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23585. */
  23586. getSpacedPoints( divisions = 5 ) {
  23587. const points = [];
  23588. for ( let d = 0; d <= divisions; d ++ ) {
  23589. points.push( this.getPointAt( d / divisions ) );
  23590. }
  23591. return points;
  23592. }
  23593. /**
  23594. * Returns the total arc length of the curve.
  23595. *
  23596. * @return {number} The length of the curve.
  23597. */
  23598. getLength() {
  23599. const lengths = this.getLengths();
  23600. return lengths[ lengths.length - 1 ];
  23601. }
  23602. /**
  23603. * Returns an array of cumulative segment lengths of the curve.
  23604. *
  23605. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23606. * @return {Array<number>} An array holding the cumulative segment lengths.
  23607. */
  23608. getLengths( divisions = this.arcLengthDivisions ) {
  23609. if ( this.cacheArcLengths &&
  23610. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23611. ! this.needsUpdate ) {
  23612. return this.cacheArcLengths;
  23613. }
  23614. this.needsUpdate = false;
  23615. const cache = [];
  23616. let current, last = this.getPoint( 0 );
  23617. let sum = 0;
  23618. cache.push( 0 );
  23619. for ( let p = 1; p <= divisions; p ++ ) {
  23620. current = this.getPoint( p / divisions );
  23621. sum += current.distanceTo( last );
  23622. cache.push( sum );
  23623. last = current;
  23624. }
  23625. this.cacheArcLengths = cache;
  23626. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23627. }
  23628. /**
  23629. * Update the cumulative segment distance cache. The method must be called
  23630. * every time curve parameters are changed. If an updated curve is part of a
  23631. * composed curve like {@link CurvePath}, this method must be called on the
  23632. * composed curve, too.
  23633. */
  23634. updateArcLengths() {
  23635. this.needsUpdate = true;
  23636. this.getLengths();
  23637. }
  23638. /**
  23639. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23640. * interpolation factor in the same range that can be ued to sample equidistant points
  23641. * from a curve.
  23642. *
  23643. * @param {number} u - The interpolation factor.
  23644. * @param {?number} distance - An optional distance on the curve.
  23645. * @return {number} The updated interpolation factor.
  23646. */
  23647. getUtoTmapping( u, distance = null ) {
  23648. const arcLengths = this.getLengths();
  23649. let i = 0;
  23650. const il = arcLengths.length;
  23651. let targetArcLength; // The targeted u distance value to get
  23652. if ( distance ) {
  23653. targetArcLength = distance;
  23654. } else {
  23655. targetArcLength = u * arcLengths[ il - 1 ];
  23656. }
  23657. // binary search for the index with largest value smaller than target u distance
  23658. let low = 0, high = il - 1, comparison;
  23659. while ( low <= high ) {
  23660. 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
  23661. comparison = arcLengths[ i ] - targetArcLength;
  23662. if ( comparison < 0 ) {
  23663. low = i + 1;
  23664. } else if ( comparison > 0 ) {
  23665. high = i - 1;
  23666. } else {
  23667. high = i;
  23668. break;
  23669. // DONE
  23670. }
  23671. }
  23672. i = high;
  23673. if ( arcLengths[ i ] === targetArcLength ) {
  23674. return i / ( il - 1 );
  23675. }
  23676. // we could get finer grain at lengths, or use simple interpolation between two points
  23677. const lengthBefore = arcLengths[ i ];
  23678. const lengthAfter = arcLengths[ i + 1 ];
  23679. const segmentLength = lengthAfter - lengthBefore;
  23680. // determine where we are between the 'before' and 'after' points
  23681. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23682. // add that fractional amount to t
  23683. const t = ( i + segmentFraction ) / ( il - 1 );
  23684. return t;
  23685. }
  23686. /**
  23687. * Returns a unit vector tangent for the given interpolation factor.
  23688. * If the derived curve does not implement its tangent derivation,
  23689. * two points a small delta apart will be used to find its gradient
  23690. * which seems to give a reasonable approximation.
  23691. *
  23692. * @param {number} t - The interpolation factor.
  23693. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23694. * @return {(Vector2|Vector3)} The tangent vector.
  23695. */
  23696. getTangent( t, optionalTarget ) {
  23697. const delta = 0.0001;
  23698. let t1 = t - delta;
  23699. let t2 = t + delta;
  23700. // Capping in case of danger
  23701. if ( t1 < 0 ) t1 = 0;
  23702. if ( t2 > 1 ) t2 = 1;
  23703. const pt1 = this.getPoint( t1 );
  23704. const pt2 = this.getPoint( t2 );
  23705. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23706. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23707. return tangent;
  23708. }
  23709. /**
  23710. * Same as {@link Curve#getTangent} but with equidistant samples.
  23711. *
  23712. * @param {number} u - The interpolation factor.
  23713. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23714. * @return {(Vector2|Vector3)} The tangent vector.
  23715. * @see {@link Curve#getPointAt}
  23716. */
  23717. getTangentAt( u, optionalTarget ) {
  23718. const t = this.getUtoTmapping( u );
  23719. return this.getTangent( t, optionalTarget );
  23720. }
  23721. /**
  23722. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23723. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23724. *
  23725. * @param {number} segments - The number of segments.
  23726. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23727. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23728. */
  23729. computeFrenetFrames( segments, closed = false ) {
  23730. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23731. const normal = new Vector3();
  23732. const tangents = [];
  23733. const normals = [];
  23734. const binormals = [];
  23735. const vec = new Vector3();
  23736. const mat = new Matrix4();
  23737. // compute the tangent vectors for each segment on the curve
  23738. for ( let i = 0; i <= segments; i ++ ) {
  23739. const u = i / segments;
  23740. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23741. }
  23742. // select an initial normal vector perpendicular to the first tangent vector,
  23743. // and in the direction of the minimum tangent xyz component
  23744. normals[ 0 ] = new Vector3();
  23745. binormals[ 0 ] = new Vector3();
  23746. let min = Number.MAX_VALUE;
  23747. const tx = Math.abs( tangents[ 0 ].x );
  23748. const ty = Math.abs( tangents[ 0 ].y );
  23749. const tz = Math.abs( tangents[ 0 ].z );
  23750. if ( tx <= min ) {
  23751. min = tx;
  23752. normal.set( 1, 0, 0 );
  23753. }
  23754. if ( ty <= min ) {
  23755. min = ty;
  23756. normal.set( 0, 1, 0 );
  23757. }
  23758. if ( tz <= min ) {
  23759. normal.set( 0, 0, 1 );
  23760. }
  23761. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23762. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23763. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23764. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23765. for ( let i = 1; i <= segments; i ++ ) {
  23766. normals[ i ] = normals[ i - 1 ].clone();
  23767. binormals[ i ] = binormals[ i - 1 ].clone();
  23768. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23769. if ( vec.length() > Number.EPSILON ) {
  23770. vec.normalize();
  23771. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23772. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23773. }
  23774. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23775. }
  23776. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23777. if ( closed === true ) {
  23778. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23779. theta /= segments;
  23780. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23781. theta = - theta;
  23782. }
  23783. for ( let i = 1; i <= segments; i ++ ) {
  23784. // twist a little...
  23785. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23786. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23787. }
  23788. }
  23789. return {
  23790. tangents: tangents,
  23791. normals: normals,
  23792. binormals: binormals
  23793. };
  23794. }
  23795. /**
  23796. * Returns a new curve with copied values from this instance.
  23797. *
  23798. * @return {Curve} A clone of this instance.
  23799. */
  23800. clone() {
  23801. return new this.constructor().copy( this );
  23802. }
  23803. /**
  23804. * Copies the values of the given curve to this instance.
  23805. *
  23806. * @param {Curve} source - The curve to copy.
  23807. * @return {Curve} A reference to this curve.
  23808. */
  23809. copy( source ) {
  23810. this.arcLengthDivisions = source.arcLengthDivisions;
  23811. return this;
  23812. }
  23813. /**
  23814. * Serializes the curve into JSON.
  23815. *
  23816. * @return {Object} A JSON object representing the serialized curve.
  23817. * @see {@link ObjectLoader#parse}
  23818. */
  23819. toJSON() {
  23820. const data = {
  23821. metadata: {
  23822. version: 4.7,
  23823. type: 'Curve',
  23824. generator: 'Curve.toJSON'
  23825. }
  23826. };
  23827. data.arcLengthDivisions = this.arcLengthDivisions;
  23828. data.type = this.type;
  23829. return data;
  23830. }
  23831. /**
  23832. * Deserializes the curve from the given JSON.
  23833. *
  23834. * @param {Object} json - The JSON holding the serialized curve.
  23835. * @return {Curve} A reference to this curve.
  23836. */
  23837. fromJSON( json ) {
  23838. this.arcLengthDivisions = json.arcLengthDivisions;
  23839. return this;
  23840. }
  23841. }
  23842. /**
  23843. * A curve representing an ellipse.
  23844. *
  23845. * ```js
  23846. * const curve = new THREE.EllipseCurve(
  23847. * 0, 0,
  23848. * 10, 10,
  23849. * 0, 2 * Math.PI,
  23850. * false,
  23851. * 0
  23852. * );
  23853. *
  23854. * const points = curve.getPoints( 50 );
  23855. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23856. *
  23857. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23858. *
  23859. * // Create the final object to add to the scene
  23860. * const ellipse = new THREE.Line( geometry, material );
  23861. * ```
  23862. *
  23863. * @augments Curve
  23864. */
  23865. class EllipseCurve extends Curve {
  23866. /**
  23867. * Constructs a new ellipse curve.
  23868. *
  23869. * @param {number} [aX=0] - The X center of the ellipse.
  23870. * @param {number} [aY=0] - The Y center of the ellipse.
  23871. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23872. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23873. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23874. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23875. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23876. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23877. */
  23878. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23879. super();
  23880. /**
  23881. * This flag can be used for type testing.
  23882. *
  23883. * @type {boolean}
  23884. * @readonly
  23885. * @default true
  23886. */
  23887. this.isEllipseCurve = true;
  23888. this.type = 'EllipseCurve';
  23889. /**
  23890. * The X center of the ellipse.
  23891. *
  23892. * @type {number}
  23893. * @default 0
  23894. */
  23895. this.aX = aX;
  23896. /**
  23897. * The Y center of the ellipse.
  23898. *
  23899. * @type {number}
  23900. * @default 0
  23901. */
  23902. this.aY = aY;
  23903. /**
  23904. * The radius of the ellipse in the x direction.
  23905. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23906. *
  23907. * @type {number}
  23908. * @default 1
  23909. */
  23910. this.xRadius = xRadius;
  23911. /**
  23912. * The radius of the ellipse in the y direction.
  23913. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23914. *
  23915. * @type {number}
  23916. * @default 1
  23917. */
  23918. this.yRadius = yRadius;
  23919. /**
  23920. * The start angle of the curve in radians starting from the positive X axis.
  23921. *
  23922. * @type {number}
  23923. * @default 0
  23924. */
  23925. this.aStartAngle = aStartAngle;
  23926. /**
  23927. * The end angle of the curve in radians starting from the positive X axis.
  23928. *
  23929. * @type {number}
  23930. * @default Math.PI*2
  23931. */
  23932. this.aEndAngle = aEndAngle;
  23933. /**
  23934. * Whether the ellipse is drawn clockwise or not.
  23935. *
  23936. * @type {boolean}
  23937. * @default false
  23938. */
  23939. this.aClockwise = aClockwise;
  23940. /**
  23941. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23942. *
  23943. * @type {number}
  23944. * @default 0
  23945. */
  23946. this.aRotation = aRotation;
  23947. }
  23948. /**
  23949. * Returns a point on the curve.
  23950. *
  23951. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23952. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23953. * @return {Vector2} The position on the curve.
  23954. */
  23955. getPoint( t, optionalTarget = new Vector2() ) {
  23956. const point = optionalTarget;
  23957. const twoPi = Math.PI * 2;
  23958. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23959. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23960. // ensures that deltaAngle is 0 .. 2 PI
  23961. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23962. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23963. if ( deltaAngle < Number.EPSILON ) {
  23964. if ( samePoints ) {
  23965. deltaAngle = 0;
  23966. } else {
  23967. deltaAngle = twoPi;
  23968. }
  23969. }
  23970. if ( this.aClockwise === true && ! samePoints ) {
  23971. if ( deltaAngle === twoPi ) {
  23972. deltaAngle = - twoPi;
  23973. } else {
  23974. deltaAngle = deltaAngle - twoPi;
  23975. }
  23976. }
  23977. const angle = this.aStartAngle + t * deltaAngle;
  23978. let x = this.aX + this.xRadius * Math.cos( angle );
  23979. let y = this.aY + this.yRadius * Math.sin( angle );
  23980. if ( this.aRotation !== 0 ) {
  23981. const cos = Math.cos( this.aRotation );
  23982. const sin = Math.sin( this.aRotation );
  23983. const tx = x - this.aX;
  23984. const ty = y - this.aY;
  23985. // Rotate the point about the center of the ellipse.
  23986. x = tx * cos - ty * sin + this.aX;
  23987. y = tx * sin + ty * cos + this.aY;
  23988. }
  23989. return point.set( x, y );
  23990. }
  23991. copy( source ) {
  23992. super.copy( source );
  23993. this.aX = source.aX;
  23994. this.aY = source.aY;
  23995. this.xRadius = source.xRadius;
  23996. this.yRadius = source.yRadius;
  23997. this.aStartAngle = source.aStartAngle;
  23998. this.aEndAngle = source.aEndAngle;
  23999. this.aClockwise = source.aClockwise;
  24000. this.aRotation = source.aRotation;
  24001. return this;
  24002. }
  24003. toJSON() {
  24004. const data = super.toJSON();
  24005. data.aX = this.aX;
  24006. data.aY = this.aY;
  24007. data.xRadius = this.xRadius;
  24008. data.yRadius = this.yRadius;
  24009. data.aStartAngle = this.aStartAngle;
  24010. data.aEndAngle = this.aEndAngle;
  24011. data.aClockwise = this.aClockwise;
  24012. data.aRotation = this.aRotation;
  24013. return data;
  24014. }
  24015. fromJSON( json ) {
  24016. super.fromJSON( json );
  24017. this.aX = json.aX;
  24018. this.aY = json.aY;
  24019. this.xRadius = json.xRadius;
  24020. this.yRadius = json.yRadius;
  24021. this.aStartAngle = json.aStartAngle;
  24022. this.aEndAngle = json.aEndAngle;
  24023. this.aClockwise = json.aClockwise;
  24024. this.aRotation = json.aRotation;
  24025. return this;
  24026. }
  24027. }
  24028. /**
  24029. * A curve representing an arc.
  24030. *
  24031. * @augments EllipseCurve
  24032. */
  24033. class ArcCurve extends EllipseCurve {
  24034. /**
  24035. * Constructs a new arc curve.
  24036. *
  24037. * @param {number} [aX=0] - The X center of the ellipse.
  24038. * @param {number} [aY=0] - The Y center of the ellipse.
  24039. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  24040. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  24041. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  24042. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  24043. */
  24044. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24045. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24046. /**
  24047. * This flag can be used for type testing.
  24048. *
  24049. * @type {boolean}
  24050. * @readonly
  24051. * @default true
  24052. */
  24053. this.isArcCurve = true;
  24054. this.type = 'ArcCurve';
  24055. }
  24056. }
  24057. function CubicPoly() {
  24058. /**
  24059. * Centripetal CatmullRom Curve - which is useful for avoiding
  24060. * cusps and self-intersections in non-uniform catmull rom curves.
  24061. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24062. *
  24063. * curve.type accepts centripetal(default), chordal and catmullrom
  24064. * curve.tension is used for catmullrom which defaults to 0.5
  24065. */
  24066. /*
  24067. Based on an optimized c++ solution in
  24068. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24069. - http://ideone.com/NoEbVM
  24070. This CubicPoly class could be used for reusing some variables and calculations,
  24071. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24072. which can be placed in CurveUtils.
  24073. */
  24074. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24075. /*
  24076. * Compute coefficients for a cubic polynomial
  24077. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24078. * such that
  24079. * p(0) = x0, p(1) = x1
  24080. * and
  24081. * p'(0) = t0, p'(1) = t1.
  24082. */
  24083. function init( x0, x1, t0, t1 ) {
  24084. c0 = x0;
  24085. c1 = t0;
  24086. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  24087. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24088. }
  24089. return {
  24090. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24091. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24092. },
  24093. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24094. // compute tangents when parameterized in [t1,t2]
  24095. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24096. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24097. // rescale tangents for parametrization in [0,1]
  24098. t1 *= dt1;
  24099. t2 *= dt1;
  24100. init( x1, x2, t1, t2 );
  24101. },
  24102. calc: function ( t ) {
  24103. const t2 = t * t;
  24104. const t3 = t2 * t;
  24105. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24106. }
  24107. };
  24108. }
  24109. //
  24110. const tmp = /*@__PURE__*/ new Vector3();
  24111. const px = /*@__PURE__*/ new CubicPoly();
  24112. const py = /*@__PURE__*/ new CubicPoly();
  24113. const pz = /*@__PURE__*/ new CubicPoly();
  24114. /**
  24115. * A curve representing a Catmull-Rom spline.
  24116. *
  24117. * ```js
  24118. * //Create a closed wavey loop
  24119. * const curve = new THREE.CatmullRomCurve3( [
  24120. * new THREE.Vector3( -10, 0, 10 ),
  24121. * new THREE.Vector3( -5, 5, 5 ),
  24122. * new THREE.Vector3( 0, 0, 0 ),
  24123. * new THREE.Vector3( 5, -5, 5 ),
  24124. * new THREE.Vector3( 10, 0, 10 )
  24125. * ] );
  24126. *
  24127. * const points = curve.getPoints( 50 );
  24128. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24129. *
  24130. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24131. *
  24132. * // Create the final object to add to the scene
  24133. * const curveObject = new THREE.Line( geometry, material );
  24134. * ```
  24135. *
  24136. * @augments Curve
  24137. */
  24138. class CatmullRomCurve3 extends Curve {
  24139. /**
  24140. * Constructs a new Catmull-Rom curve.
  24141. *
  24142. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  24143. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  24144. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  24145. * @param {number} [tension=0.5] - Tension of the curve.
  24146. */
  24147. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  24148. super();
  24149. /**
  24150. * This flag can be used for type testing.
  24151. *
  24152. * @type {boolean}
  24153. * @readonly
  24154. * @default true
  24155. */
  24156. this.isCatmullRomCurve3 = true;
  24157. this.type = 'CatmullRomCurve3';
  24158. /**
  24159. * An array of 3D points defining the curve.
  24160. *
  24161. * @type {Array<Vector3>}
  24162. */
  24163. this.points = points;
  24164. /**
  24165. * Whether the curve is closed or not.
  24166. *
  24167. * @type {boolean}
  24168. * @default false
  24169. */
  24170. this.closed = closed;
  24171. /**
  24172. * The curve type.
  24173. *
  24174. * @type {('centripetal'|'chordal'|'catmullrom')}
  24175. * @default 'centripetal'
  24176. */
  24177. this.curveType = curveType;
  24178. /**
  24179. * Tension of the curve.
  24180. *
  24181. * @type {number}
  24182. * @default 0.5
  24183. */
  24184. this.tension = tension;
  24185. }
  24186. /**
  24187. * Returns a point on the curve.
  24188. *
  24189. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24190. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24191. * @return {Vector3} The position on the curve.
  24192. */
  24193. getPoint( t, optionalTarget = new Vector3() ) {
  24194. const point = optionalTarget;
  24195. const points = this.points;
  24196. const l = points.length;
  24197. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24198. let intPoint = Math.floor( p );
  24199. let weight = p - intPoint;
  24200. if ( this.closed ) {
  24201. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  24202. } else if ( weight === 0 && intPoint === l - 1 ) {
  24203. intPoint = l - 2;
  24204. weight = 1;
  24205. }
  24206. let p0, p3; // 4 points (p1 & p2 defined below)
  24207. if ( this.closed || intPoint > 0 ) {
  24208. p0 = points[ ( intPoint - 1 ) % l ];
  24209. } else {
  24210. // extrapolate first point
  24211. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24212. p0 = tmp;
  24213. }
  24214. const p1 = points[ intPoint % l ];
  24215. const p2 = points[ ( intPoint + 1 ) % l ];
  24216. if ( this.closed || intPoint + 2 < l ) {
  24217. p3 = points[ ( intPoint + 2 ) % l ];
  24218. } else {
  24219. // extrapolate last point
  24220. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24221. p3 = tmp;
  24222. }
  24223. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24224. // init Centripetal / Chordal Catmull-Rom
  24225. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24226. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24227. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24228. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24229. // safety check for repeated points
  24230. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24231. if ( dt0 < 1e-4 ) dt0 = dt1;
  24232. if ( dt2 < 1e-4 ) dt2 = dt1;
  24233. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24234. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24235. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24236. } else if ( this.curveType === 'catmullrom' ) {
  24237. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24238. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24239. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24240. }
  24241. point.set(
  24242. px.calc( weight ),
  24243. py.calc( weight ),
  24244. pz.calc( weight )
  24245. );
  24246. return point;
  24247. }
  24248. copy( source ) {
  24249. super.copy( source );
  24250. this.points = [];
  24251. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24252. const point = source.points[ i ];
  24253. this.points.push( point.clone() );
  24254. }
  24255. this.closed = source.closed;
  24256. this.curveType = source.curveType;
  24257. this.tension = source.tension;
  24258. return this;
  24259. }
  24260. toJSON() {
  24261. const data = super.toJSON();
  24262. data.points = [];
  24263. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24264. const point = this.points[ i ];
  24265. data.points.push( point.toArray() );
  24266. }
  24267. data.closed = this.closed;
  24268. data.curveType = this.curveType;
  24269. data.tension = this.tension;
  24270. return data;
  24271. }
  24272. fromJSON( json ) {
  24273. super.fromJSON( json );
  24274. this.points = [];
  24275. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24276. const point = json.points[ i ];
  24277. this.points.push( new Vector3().fromArray( point ) );
  24278. }
  24279. this.closed = json.closed;
  24280. this.curveType = json.curveType;
  24281. this.tension = json.tension;
  24282. return this;
  24283. }
  24284. }
  24285. /**
  24286. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24287. *
  24288. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24289. *
  24290. * @module Interpolations
  24291. */
  24292. /**
  24293. * Computes a point on a Catmull-Rom spline.
  24294. *
  24295. * @param {number} t - The interpolation factor.
  24296. * @param {number} p0 - The first control point.
  24297. * @param {number} p1 - The second control point.
  24298. * @param {number} p2 - The third control point.
  24299. * @param {number} p3 - The fourth control point.
  24300. * @return {number} The calculated point on a Catmull-Rom spline.
  24301. */
  24302. function CatmullRom( t, p0, p1, p2, p3 ) {
  24303. const v0 = ( p2 - p0 ) * 0.5;
  24304. const v1 = ( p3 - p1 ) * 0.5;
  24305. const t2 = t * t;
  24306. const t3 = t * t2;
  24307. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24308. }
  24309. //
  24310. function QuadraticBezierP0( t, p ) {
  24311. const k = 1 - t;
  24312. return k * k * p;
  24313. }
  24314. function QuadraticBezierP1( t, p ) {
  24315. return 2 * ( 1 - t ) * t * p;
  24316. }
  24317. function QuadraticBezierP2( t, p ) {
  24318. return t * t * p;
  24319. }
  24320. /**
  24321. * Computes a point on a Quadratic Bezier curve.
  24322. *
  24323. * @param {number} t - The interpolation factor.
  24324. * @param {number} p0 - The first control point.
  24325. * @param {number} p1 - The second control point.
  24326. * @param {number} p2 - The third control point.
  24327. * @return {number} The calculated point on a Quadratic Bezier curve.
  24328. */
  24329. function QuadraticBezier( t, p0, p1, p2 ) {
  24330. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24331. QuadraticBezierP2( t, p2 );
  24332. }
  24333. //
  24334. function CubicBezierP0( t, p ) {
  24335. const k = 1 - t;
  24336. return k * k * k * p;
  24337. }
  24338. function CubicBezierP1( t, p ) {
  24339. const k = 1 - t;
  24340. return 3 * k * k * t * p;
  24341. }
  24342. function CubicBezierP2( t, p ) {
  24343. return 3 * ( 1 - t ) * t * t * p;
  24344. }
  24345. function CubicBezierP3( t, p ) {
  24346. return t * t * t * p;
  24347. }
  24348. /**
  24349. * Computes a point on a Cubic Bezier curve.
  24350. *
  24351. * @param {number} t - The interpolation factor.
  24352. * @param {number} p0 - The first control point.
  24353. * @param {number} p1 - The second control point.
  24354. * @param {number} p2 - The third control point.
  24355. * @param {number} p3 - The fourth control point.
  24356. * @return {number} The calculated point on a Cubic Bezier curve.
  24357. */
  24358. function CubicBezier( t, p0, p1, p2, p3 ) {
  24359. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24360. CubicBezierP3( t, p3 );
  24361. }
  24362. /**
  24363. * A curve representing a 2D Cubic Bezier curve.
  24364. *
  24365. * ```js
  24366. * const curve = new THREE.CubicBezierCurve(
  24367. * new THREE.Vector2( - 0, 0 ),
  24368. * new THREE.Vector2( - 5, 15 ),
  24369. * new THREE.Vector2( 20, 15 ),
  24370. * new THREE.Vector2( 10, 0 )
  24371. * );
  24372. *
  24373. * const points = curve.getPoints( 50 );
  24374. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24375. *
  24376. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24377. *
  24378. * // Create the final object to add to the scene
  24379. * const curveObject = new THREE.Line( geometry, material );
  24380. * ```
  24381. *
  24382. * @augments Curve
  24383. */
  24384. class CubicBezierCurve extends Curve {
  24385. /**
  24386. * Constructs a new Cubic Bezier curve.
  24387. *
  24388. * @param {Vector2} [v0] - The start point.
  24389. * @param {Vector2} [v1] - The first control point.
  24390. * @param {Vector2} [v2] - The second control point.
  24391. * @param {Vector2} [v3] - The end point.
  24392. */
  24393. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24394. super();
  24395. /**
  24396. * This flag can be used for type testing.
  24397. *
  24398. * @type {boolean}
  24399. * @readonly
  24400. * @default true
  24401. */
  24402. this.isCubicBezierCurve = true;
  24403. this.type = 'CubicBezierCurve';
  24404. /**
  24405. * The start point.
  24406. *
  24407. * @type {Vector2}
  24408. */
  24409. this.v0 = v0;
  24410. /**
  24411. * The first control point.
  24412. *
  24413. * @type {Vector2}
  24414. */
  24415. this.v1 = v1;
  24416. /**
  24417. * The second control point.
  24418. *
  24419. * @type {Vector2}
  24420. */
  24421. this.v2 = v2;
  24422. /**
  24423. * The end point.
  24424. *
  24425. * @type {Vector2}
  24426. */
  24427. this.v3 = v3;
  24428. }
  24429. /**
  24430. * Returns a point on the curve.
  24431. *
  24432. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24433. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24434. * @return {Vector2} The position on the curve.
  24435. */
  24436. getPoint( t, optionalTarget = new Vector2() ) {
  24437. const point = optionalTarget;
  24438. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24439. point.set(
  24440. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24441. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24442. );
  24443. return point;
  24444. }
  24445. copy( source ) {
  24446. super.copy( source );
  24447. this.v0.copy( source.v0 );
  24448. this.v1.copy( source.v1 );
  24449. this.v2.copy( source.v2 );
  24450. this.v3.copy( source.v3 );
  24451. return this;
  24452. }
  24453. toJSON() {
  24454. const data = super.toJSON();
  24455. data.v0 = this.v0.toArray();
  24456. data.v1 = this.v1.toArray();
  24457. data.v2 = this.v2.toArray();
  24458. data.v3 = this.v3.toArray();
  24459. return data;
  24460. }
  24461. fromJSON( json ) {
  24462. super.fromJSON( json );
  24463. this.v0.fromArray( json.v0 );
  24464. this.v1.fromArray( json.v1 );
  24465. this.v2.fromArray( json.v2 );
  24466. this.v3.fromArray( json.v3 );
  24467. return this;
  24468. }
  24469. }
  24470. /**
  24471. * A curve representing a 3D Cubic Bezier curve.
  24472. *
  24473. * @augments Curve
  24474. */
  24475. class CubicBezierCurve3 extends Curve {
  24476. /**
  24477. * Constructs a new Cubic Bezier curve.
  24478. *
  24479. * @param {Vector3} [v0] - The start point.
  24480. * @param {Vector3} [v1] - The first control point.
  24481. * @param {Vector3} [v2] - The second control point.
  24482. * @param {Vector3} [v3] - The end point.
  24483. */
  24484. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24485. super();
  24486. /**
  24487. * This flag can be used for type testing.
  24488. *
  24489. * @type {boolean}
  24490. * @readonly
  24491. * @default true
  24492. */
  24493. this.isCubicBezierCurve3 = true;
  24494. this.type = 'CubicBezierCurve3';
  24495. /**
  24496. * The start point.
  24497. *
  24498. * @type {Vector3}
  24499. */
  24500. this.v0 = v0;
  24501. /**
  24502. * The first control point.
  24503. *
  24504. * @type {Vector3}
  24505. */
  24506. this.v1 = v1;
  24507. /**
  24508. * The second control point.
  24509. *
  24510. * @type {Vector3}
  24511. */
  24512. this.v2 = v2;
  24513. /**
  24514. * The end point.
  24515. *
  24516. * @type {Vector3}
  24517. */
  24518. this.v3 = v3;
  24519. }
  24520. /**
  24521. * Returns a point on the curve.
  24522. *
  24523. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24524. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24525. * @return {Vector3} The position on the curve.
  24526. */
  24527. getPoint( t, optionalTarget = new Vector3() ) {
  24528. const point = optionalTarget;
  24529. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24530. point.set(
  24531. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24532. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24533. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24534. );
  24535. return point;
  24536. }
  24537. copy( source ) {
  24538. super.copy( source );
  24539. this.v0.copy( source.v0 );
  24540. this.v1.copy( source.v1 );
  24541. this.v2.copy( source.v2 );
  24542. this.v3.copy( source.v3 );
  24543. return this;
  24544. }
  24545. toJSON() {
  24546. const data = super.toJSON();
  24547. data.v0 = this.v0.toArray();
  24548. data.v1 = this.v1.toArray();
  24549. data.v2 = this.v2.toArray();
  24550. data.v3 = this.v3.toArray();
  24551. return data;
  24552. }
  24553. fromJSON( json ) {
  24554. super.fromJSON( json );
  24555. this.v0.fromArray( json.v0 );
  24556. this.v1.fromArray( json.v1 );
  24557. this.v2.fromArray( json.v2 );
  24558. this.v3.fromArray( json.v3 );
  24559. return this;
  24560. }
  24561. }
  24562. /**
  24563. * A curve representing a 2D line segment.
  24564. *
  24565. * @augments Curve
  24566. */
  24567. class LineCurve extends Curve {
  24568. /**
  24569. * Constructs a new line curve.
  24570. *
  24571. * @param {Vector2} [v1] - The start point.
  24572. * @param {Vector2} [v2] - The end point.
  24573. */
  24574. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24575. super();
  24576. /**
  24577. * This flag can be used for type testing.
  24578. *
  24579. * @type {boolean}
  24580. * @readonly
  24581. * @default true
  24582. */
  24583. this.isLineCurve = true;
  24584. this.type = 'LineCurve';
  24585. /**
  24586. * The start point.
  24587. *
  24588. * @type {Vector2}
  24589. */
  24590. this.v1 = v1;
  24591. /**
  24592. * The end point.
  24593. *
  24594. * @type {Vector2}
  24595. */
  24596. this.v2 = v2;
  24597. }
  24598. /**
  24599. * Returns a point on the line.
  24600. *
  24601. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24602. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24603. * @return {Vector2} The position on the line.
  24604. */
  24605. getPoint( t, optionalTarget = new Vector2() ) {
  24606. const point = optionalTarget;
  24607. if ( t === 1 ) {
  24608. point.copy( this.v2 );
  24609. } else {
  24610. point.copy( this.v2 ).sub( this.v1 );
  24611. point.multiplyScalar( t ).add( this.v1 );
  24612. }
  24613. return point;
  24614. }
  24615. // Line curve is linear, so we can overwrite default getPointAt
  24616. getPointAt( u, optionalTarget ) {
  24617. return this.getPoint( u, optionalTarget );
  24618. }
  24619. getTangent( t, optionalTarget = new Vector2() ) {
  24620. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24621. }
  24622. getTangentAt( u, optionalTarget ) {
  24623. return this.getTangent( u, optionalTarget );
  24624. }
  24625. copy( source ) {
  24626. super.copy( source );
  24627. this.v1.copy( source.v1 );
  24628. this.v2.copy( source.v2 );
  24629. return this;
  24630. }
  24631. toJSON() {
  24632. const data = super.toJSON();
  24633. data.v1 = this.v1.toArray();
  24634. data.v2 = this.v2.toArray();
  24635. return data;
  24636. }
  24637. fromJSON( json ) {
  24638. super.fromJSON( json );
  24639. this.v1.fromArray( json.v1 );
  24640. this.v2.fromArray( json.v2 );
  24641. return this;
  24642. }
  24643. }
  24644. /**
  24645. * A curve representing a 3D line segment.
  24646. *
  24647. * @augments Curve
  24648. */
  24649. class LineCurve3 extends Curve {
  24650. /**
  24651. * Constructs a new line curve.
  24652. *
  24653. * @param {Vector3} [v1] - The start point.
  24654. * @param {Vector3} [v2] - The end point.
  24655. */
  24656. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24657. super();
  24658. /**
  24659. * This flag can be used for type testing.
  24660. *
  24661. * @type {boolean}
  24662. * @readonly
  24663. * @default true
  24664. */
  24665. this.isLineCurve3 = true;
  24666. this.type = 'LineCurve3';
  24667. /**
  24668. * The start point.
  24669. *
  24670. * @type {Vector3}
  24671. */
  24672. this.v1 = v1;
  24673. /**
  24674. * The end point.
  24675. *
  24676. * @type {Vector2}
  24677. */
  24678. this.v2 = v2;
  24679. }
  24680. /**
  24681. * Returns a point on the line.
  24682. *
  24683. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24684. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24685. * @return {Vector3} The position on the line.
  24686. */
  24687. getPoint( t, optionalTarget = new Vector3() ) {
  24688. const point = optionalTarget;
  24689. if ( t === 1 ) {
  24690. point.copy( this.v2 );
  24691. } else {
  24692. point.copy( this.v2 ).sub( this.v1 );
  24693. point.multiplyScalar( t ).add( this.v1 );
  24694. }
  24695. return point;
  24696. }
  24697. // Line curve is linear, so we can overwrite default getPointAt
  24698. getPointAt( u, optionalTarget ) {
  24699. return this.getPoint( u, optionalTarget );
  24700. }
  24701. getTangent( t, optionalTarget = new Vector3() ) {
  24702. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24703. }
  24704. getTangentAt( u, optionalTarget ) {
  24705. return this.getTangent( u, optionalTarget );
  24706. }
  24707. copy( source ) {
  24708. super.copy( source );
  24709. this.v1.copy( source.v1 );
  24710. this.v2.copy( source.v2 );
  24711. return this;
  24712. }
  24713. toJSON() {
  24714. const data = super.toJSON();
  24715. data.v1 = this.v1.toArray();
  24716. data.v2 = this.v2.toArray();
  24717. return data;
  24718. }
  24719. fromJSON( json ) {
  24720. super.fromJSON( json );
  24721. this.v1.fromArray( json.v1 );
  24722. this.v2.fromArray( json.v2 );
  24723. return this;
  24724. }
  24725. }
  24726. /**
  24727. * A curve representing a 2D Quadratic Bezier curve.
  24728. *
  24729. * ```js
  24730. * const curve = new THREE.QuadraticBezierCurve(
  24731. * new THREE.Vector2( - 10, 0 ),
  24732. * new THREE.Vector2( 20, 15 ),
  24733. * new THREE.Vector2( 10, 0 )
  24734. * )
  24735. *
  24736. * const points = curve.getPoints( 50 );
  24737. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24738. *
  24739. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24740. *
  24741. * // Create the final object to add to the scene
  24742. * const curveObject = new THREE.Line( geometry, material );
  24743. * ```
  24744. *
  24745. * @augments Curve
  24746. */
  24747. class QuadraticBezierCurve extends Curve {
  24748. /**
  24749. * Constructs a new Quadratic Bezier curve.
  24750. *
  24751. * @param {Vector2} [v0] - The start point.
  24752. * @param {Vector2} [v1] - The control point.
  24753. * @param {Vector2} [v2] - The end point.
  24754. */
  24755. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24756. super();
  24757. /**
  24758. * This flag can be used for type testing.
  24759. *
  24760. * @type {boolean}
  24761. * @readonly
  24762. * @default true
  24763. */
  24764. this.isQuadraticBezierCurve = true;
  24765. this.type = 'QuadraticBezierCurve';
  24766. /**
  24767. * The start point.
  24768. *
  24769. * @type {Vector2}
  24770. */
  24771. this.v0 = v0;
  24772. /**
  24773. * The control point.
  24774. *
  24775. * @type {Vector2}
  24776. */
  24777. this.v1 = v1;
  24778. /**
  24779. * The end point.
  24780. *
  24781. * @type {Vector2}
  24782. */
  24783. this.v2 = v2;
  24784. }
  24785. /**
  24786. * Returns a point on the curve.
  24787. *
  24788. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24789. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24790. * @return {Vector2} The position on the curve.
  24791. */
  24792. getPoint( t, optionalTarget = new Vector2() ) {
  24793. const point = optionalTarget;
  24794. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24795. point.set(
  24796. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24797. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24798. );
  24799. return point;
  24800. }
  24801. copy( source ) {
  24802. super.copy( source );
  24803. this.v0.copy( source.v0 );
  24804. this.v1.copy( source.v1 );
  24805. this.v2.copy( source.v2 );
  24806. return this;
  24807. }
  24808. toJSON() {
  24809. const data = super.toJSON();
  24810. data.v0 = this.v0.toArray();
  24811. data.v1 = this.v1.toArray();
  24812. data.v2 = this.v2.toArray();
  24813. return data;
  24814. }
  24815. fromJSON( json ) {
  24816. super.fromJSON( json );
  24817. this.v0.fromArray( json.v0 );
  24818. this.v1.fromArray( json.v1 );
  24819. this.v2.fromArray( json.v2 );
  24820. return this;
  24821. }
  24822. }
  24823. /**
  24824. * A curve representing a 3D Quadratic Bezier curve.
  24825. *
  24826. * @augments Curve
  24827. */
  24828. class QuadraticBezierCurve3 extends Curve {
  24829. /**
  24830. * Constructs a new Quadratic Bezier curve.
  24831. *
  24832. * @param {Vector3} [v0] - The start point.
  24833. * @param {Vector3} [v1] - The control point.
  24834. * @param {Vector3} [v2] - The end point.
  24835. */
  24836. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24837. super();
  24838. /**
  24839. * This flag can be used for type testing.
  24840. *
  24841. * @type {boolean}
  24842. * @readonly
  24843. * @default true
  24844. */
  24845. this.isQuadraticBezierCurve3 = true;
  24846. this.type = 'QuadraticBezierCurve3';
  24847. /**
  24848. * The start point.
  24849. *
  24850. * @type {Vector3}
  24851. */
  24852. this.v0 = v0;
  24853. /**
  24854. * The control point.
  24855. *
  24856. * @type {Vector3}
  24857. */
  24858. this.v1 = v1;
  24859. /**
  24860. * The end point.
  24861. *
  24862. * @type {Vector3}
  24863. */
  24864. this.v2 = v2;
  24865. }
  24866. /**
  24867. * Returns a point on the curve.
  24868. *
  24869. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24870. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24871. * @return {Vector3} The position on the curve.
  24872. */
  24873. getPoint( t, optionalTarget = new Vector3() ) {
  24874. const point = optionalTarget;
  24875. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24876. point.set(
  24877. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24878. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24879. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24880. );
  24881. return point;
  24882. }
  24883. copy( source ) {
  24884. super.copy( source );
  24885. this.v0.copy( source.v0 );
  24886. this.v1.copy( source.v1 );
  24887. this.v2.copy( source.v2 );
  24888. return this;
  24889. }
  24890. toJSON() {
  24891. const data = super.toJSON();
  24892. data.v0 = this.v0.toArray();
  24893. data.v1 = this.v1.toArray();
  24894. data.v2 = this.v2.toArray();
  24895. return data;
  24896. }
  24897. fromJSON( json ) {
  24898. super.fromJSON( json );
  24899. this.v0.fromArray( json.v0 );
  24900. this.v1.fromArray( json.v1 );
  24901. this.v2.fromArray( json.v2 );
  24902. return this;
  24903. }
  24904. }
  24905. /**
  24906. * A curve representing a 2D spline curve.
  24907. *
  24908. * ```js
  24909. * // Create a sine-like wave
  24910. * const curve = new THREE.SplineCurve( [
  24911. * new THREE.Vector2( -10, 0 ),
  24912. * new THREE.Vector2( -5, 5 ),
  24913. * new THREE.Vector2( 0, 0 ),
  24914. * new THREE.Vector2( 5, -5 ),
  24915. * new THREE.Vector2( 10, 0 )
  24916. * ] );
  24917. *
  24918. * const points = curve.getPoints( 50 );
  24919. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24920. *
  24921. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24922. *
  24923. * // Create the final object to add to the scene
  24924. * const splineObject = new THREE.Line( geometry, material );
  24925. * ```
  24926. *
  24927. * @augments Curve
  24928. */
  24929. class SplineCurve extends Curve {
  24930. /**
  24931. * Constructs a new 2D spline curve.
  24932. *
  24933. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24934. */
  24935. constructor( points = [] ) {
  24936. super();
  24937. /**
  24938. * This flag can be used for type testing.
  24939. *
  24940. * @type {boolean}
  24941. * @readonly
  24942. * @default true
  24943. */
  24944. this.isSplineCurve = true;
  24945. this.type = 'SplineCurve';
  24946. /**
  24947. * An array of 2D points defining the curve.
  24948. *
  24949. * @type {Array<Vector2>}
  24950. */
  24951. this.points = points;
  24952. }
  24953. /**
  24954. * Returns a point on the curve.
  24955. *
  24956. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24957. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24958. * @return {Vector2} The position on the curve.
  24959. */
  24960. getPoint( t, optionalTarget = new Vector2() ) {
  24961. const point = optionalTarget;
  24962. const points = this.points;
  24963. const p = ( points.length - 1 ) * t;
  24964. const intPoint = Math.floor( p );
  24965. const weight = p - intPoint;
  24966. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24967. const p1 = points[ intPoint ];
  24968. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24969. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24970. point.set(
  24971. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24972. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24973. );
  24974. return point;
  24975. }
  24976. copy( source ) {
  24977. super.copy( source );
  24978. this.points = [];
  24979. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24980. const point = source.points[ i ];
  24981. this.points.push( point.clone() );
  24982. }
  24983. return this;
  24984. }
  24985. toJSON() {
  24986. const data = super.toJSON();
  24987. data.points = [];
  24988. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24989. const point = this.points[ i ];
  24990. data.points.push( point.toArray() );
  24991. }
  24992. return data;
  24993. }
  24994. fromJSON( json ) {
  24995. super.fromJSON( json );
  24996. this.points = [];
  24997. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24998. const point = json.points[ i ];
  24999. this.points.push( new Vector2().fromArray( point ) );
  25000. }
  25001. return this;
  25002. }
  25003. }
  25004. var Curves = /*#__PURE__*/Object.freeze({
  25005. __proto__: null,
  25006. ArcCurve: ArcCurve,
  25007. CatmullRomCurve3: CatmullRomCurve3,
  25008. CubicBezierCurve: CubicBezierCurve,
  25009. CubicBezierCurve3: CubicBezierCurve3,
  25010. EllipseCurve: EllipseCurve,
  25011. LineCurve: LineCurve,
  25012. LineCurve3: LineCurve3,
  25013. QuadraticBezierCurve: QuadraticBezierCurve,
  25014. QuadraticBezierCurve3: QuadraticBezierCurve3,
  25015. SplineCurve: SplineCurve
  25016. });
  25017. /**
  25018. * A base class extending {@link Curve}. `CurvePath` is simply an
  25019. * array of connected curves, but retains the API of a curve.
  25020. *
  25021. * @augments Curve
  25022. */
  25023. class CurvePath extends Curve {
  25024. /**
  25025. * Constructs a new curve path.
  25026. */
  25027. constructor() {
  25028. super();
  25029. this.type = 'CurvePath';
  25030. /**
  25031. * An array of curves defining the
  25032. * path.
  25033. *
  25034. * @type {Array<Curve>}
  25035. */
  25036. this.curves = [];
  25037. /**
  25038. * Whether the path should automatically be closed
  25039. * by a line curve.
  25040. *
  25041. * @type {boolean}
  25042. * @default false
  25043. */
  25044. this.autoClose = false;
  25045. }
  25046. /**
  25047. * Adds a curve to this curve path.
  25048. *
  25049. * @param {Curve} curve - The curve to add.
  25050. */
  25051. add( curve ) {
  25052. this.curves.push( curve );
  25053. }
  25054. /**
  25055. * Adds a line curve to close the path.
  25056. *
  25057. * @return {CurvePath} A reference to this curve path.
  25058. */
  25059. closePath() {
  25060. // Add a line curve if start and end of lines are not connected
  25061. const startPoint = this.curves[ 0 ].getPoint( 0 );
  25062. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25063. if ( ! startPoint.equals( endPoint ) ) {
  25064. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  25065. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  25066. }
  25067. return this;
  25068. }
  25069. /**
  25070. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  25071. * for the given interpolation factor.
  25072. *
  25073. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  25074. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  25075. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  25076. */
  25077. getPoint( t, optionalTarget ) {
  25078. // To get accurate point with reference to
  25079. // entire path distance at time t,
  25080. // following has to be done:
  25081. // 1. Length of each sub path have to be known
  25082. // 2. Locate and identify type of curve
  25083. // 3. Get t for the curve
  25084. // 4. Return curve.getPointAt(t')
  25085. const d = t * this.getLength();
  25086. const curveLengths = this.getCurveLengths();
  25087. let i = 0;
  25088. // To think about boundaries points.
  25089. while ( i < curveLengths.length ) {
  25090. if ( curveLengths[ i ] >= d ) {
  25091. const diff = curveLengths[ i ] - d;
  25092. const curve = this.curves[ i ];
  25093. const segmentLength = curve.getLength();
  25094. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25095. return curve.getPointAt( u, optionalTarget );
  25096. }
  25097. i ++;
  25098. }
  25099. return null;
  25100. // loop where sum != 0, sum > d , sum+1 <d
  25101. }
  25102. getLength() {
  25103. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25104. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25105. // getPoint() depends on getLength
  25106. const lens = this.getCurveLengths();
  25107. return lens[ lens.length - 1 ];
  25108. }
  25109. updateArcLengths() {
  25110. // cacheLengths must be recalculated.
  25111. this.needsUpdate = true;
  25112. this.cacheLengths = null;
  25113. this.getCurveLengths();
  25114. }
  25115. /**
  25116. * Returns list of cumulative curve lengths of the defined curves.
  25117. *
  25118. * @return {Array<number>} The curve lengths.
  25119. */
  25120. getCurveLengths() {
  25121. // Compute lengths and cache them
  25122. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25123. // We use cache values if curves and cache array are same length
  25124. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25125. return this.cacheLengths;
  25126. }
  25127. // Get length of sub-curve
  25128. // Push sums into cached array
  25129. const lengths = [];
  25130. let sums = 0;
  25131. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25132. sums += this.curves[ i ].getLength();
  25133. lengths.push( sums );
  25134. }
  25135. this.cacheLengths = lengths;
  25136. return lengths;
  25137. }
  25138. getSpacedPoints( divisions = 40 ) {
  25139. const points = [];
  25140. for ( let i = 0; i <= divisions; i ++ ) {
  25141. points.push( this.getPoint( i / divisions ) );
  25142. }
  25143. if ( this.autoClose ) {
  25144. points.push( points[ 0 ] );
  25145. }
  25146. return points;
  25147. }
  25148. getPoints( divisions = 12 ) {
  25149. const points = [];
  25150. let last;
  25151. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25152. const curve = curves[ i ];
  25153. const resolution = curve.isEllipseCurve ? divisions * 2
  25154. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  25155. : curve.isSplineCurve ? divisions * curve.points.length
  25156. : divisions;
  25157. const pts = curve.getPoints( resolution );
  25158. for ( let j = 0; j < pts.length; j ++ ) {
  25159. const point = pts[ j ];
  25160. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25161. points.push( point );
  25162. last = point;
  25163. }
  25164. }
  25165. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25166. points.push( points[ 0 ] );
  25167. }
  25168. return points;
  25169. }
  25170. copy( source ) {
  25171. super.copy( source );
  25172. this.curves = [];
  25173. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  25174. const curve = source.curves[ i ];
  25175. this.curves.push( curve.clone() );
  25176. }
  25177. this.autoClose = source.autoClose;
  25178. return this;
  25179. }
  25180. toJSON() {
  25181. const data = super.toJSON();
  25182. data.autoClose = this.autoClose;
  25183. data.curves = [];
  25184. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25185. const curve = this.curves[ i ];
  25186. data.curves.push( curve.toJSON() );
  25187. }
  25188. return data;
  25189. }
  25190. fromJSON( json ) {
  25191. super.fromJSON( json );
  25192. this.autoClose = json.autoClose;
  25193. this.curves = [];
  25194. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  25195. const curve = json.curves[ i ];
  25196. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  25197. }
  25198. return this;
  25199. }
  25200. }
  25201. /**
  25202. * A 2D path representation. The class provides methods for creating paths
  25203. * and contours of 2D shapes similar to the 2D Canvas API.
  25204. *
  25205. * ```js
  25206. * const path = new THREE.Path();
  25207. *
  25208. * path.lineTo( 0, 0.8 );
  25209. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  25210. * path.lineTo( 1, 1 );
  25211. *
  25212. * const points = path.getPoints();
  25213. *
  25214. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  25215. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  25216. *
  25217. * const line = new THREE.Line( geometry, material );
  25218. * scene.add( line );
  25219. * ```
  25220. *
  25221. * @augments CurvePath
  25222. */
  25223. class Path extends CurvePath {
  25224. /**
  25225. * Constructs a new path.
  25226. *
  25227. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25228. */
  25229. constructor( points ) {
  25230. super();
  25231. this.type = 'Path';
  25232. /**
  25233. * The current offset of the path. Any new curve added will start here.
  25234. *
  25235. * @type {Vector2}
  25236. */
  25237. this.currentPoint = new Vector2();
  25238. if ( points ) {
  25239. this.setFromPoints( points );
  25240. }
  25241. }
  25242. /**
  25243. * Creates a path from the given list of points. The points are added
  25244. * to the path as instances of {@link LineCurve}.
  25245. *
  25246. * @param {Array<Vector2>} points - An array of 2D points.
  25247. * @return {Path} A reference to this path.
  25248. */
  25249. setFromPoints( points ) {
  25250. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25251. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25252. this.lineTo( points[ i ].x, points[ i ].y );
  25253. }
  25254. return this;
  25255. }
  25256. /**
  25257. * Moves {@link Path#currentPoint} to the given point.
  25258. *
  25259. * @param {number} x - The x coordinate.
  25260. * @param {number} y - The y coordinate.
  25261. * @return {Path} A reference to this path.
  25262. */
  25263. moveTo( x, y ) {
  25264. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25265. return this;
  25266. }
  25267. /**
  25268. * Adds an instance of {@link LineCurve} to the path by connecting
  25269. * the current point with the given one.
  25270. *
  25271. * @param {number} x - The x coordinate of the end point.
  25272. * @param {number} y - The y coordinate of the end point.
  25273. * @return {Path} A reference to this path.
  25274. */
  25275. lineTo( x, y ) {
  25276. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25277. this.curves.push( curve );
  25278. this.currentPoint.set( x, y );
  25279. return this;
  25280. }
  25281. /**
  25282. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25283. * the current point with the given one.
  25284. *
  25285. * @param {number} aCPx - The x coordinate of the control point.
  25286. * @param {number} aCPy - The y coordinate of the control point.
  25287. * @param {number} aX - The x coordinate of the end point.
  25288. * @param {number} aY - The y coordinate of the end point.
  25289. * @return {Path} A reference to this path.
  25290. */
  25291. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25292. const curve = new QuadraticBezierCurve(
  25293. this.currentPoint.clone(),
  25294. new Vector2( aCPx, aCPy ),
  25295. new Vector2( aX, aY )
  25296. );
  25297. this.curves.push( curve );
  25298. this.currentPoint.set( aX, aY );
  25299. return this;
  25300. }
  25301. /**
  25302. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25303. * the current point with the given one.
  25304. *
  25305. * @param {number} aCP1x - The x coordinate of the first control point.
  25306. * @param {number} aCP1y - The y coordinate of the first control point.
  25307. * @param {number} aCP2x - The x coordinate of the second control point.
  25308. * @param {number} aCP2y - The y coordinate of the second control point.
  25309. * @param {number} aX - The x coordinate of the end point.
  25310. * @param {number} aY - The y coordinate of the end point.
  25311. * @return {Path} A reference to this path.
  25312. */
  25313. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25314. const curve = new CubicBezierCurve(
  25315. this.currentPoint.clone(),
  25316. new Vector2( aCP1x, aCP1y ),
  25317. new Vector2( aCP2x, aCP2y ),
  25318. new Vector2( aX, aY )
  25319. );
  25320. this.curves.push( curve );
  25321. this.currentPoint.set( aX, aY );
  25322. return this;
  25323. }
  25324. /**
  25325. * Adds an instance of {@link SplineCurve} to the path by connecting
  25326. * the current point with the given list of points.
  25327. *
  25328. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25329. * @return {Path} A reference to this path.
  25330. */
  25331. splineThru( pts ) {
  25332. const npts = [ this.currentPoint.clone() ].concat( pts );
  25333. const curve = new SplineCurve( npts );
  25334. this.curves.push( curve );
  25335. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25336. return this;
  25337. }
  25338. /**
  25339. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25340. * to the current point.
  25341. *
  25342. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25343. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25344. * @param {number} [aRadius=1] - The radius of the arc.
  25345. * @param {number} [aStartAngle=0] - The start angle in radians.
  25346. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25347. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25348. * @return {Path} A reference to this path.
  25349. */
  25350. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25351. const x0 = this.currentPoint.x;
  25352. const y0 = this.currentPoint.y;
  25353. this.absarc( aX + x0, aY + y0, aRadius,
  25354. aStartAngle, aEndAngle, aClockwise );
  25355. return this;
  25356. }
  25357. /**
  25358. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25359. *
  25360. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25361. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25362. * @param {number} [aRadius=1] - The radius of the arc.
  25363. * @param {number} [aStartAngle=0] - The start angle in radians.
  25364. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25365. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25366. * @return {Path} A reference to this path.
  25367. */
  25368. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25369. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25370. return this;
  25371. }
  25372. /**
  25373. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25374. * to the current point
  25375. *
  25376. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25377. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25378. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25379. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25380. * @param {number} [aStartAngle=0] - The start angle in radians.
  25381. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25382. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25383. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25384. * @return {Path} A reference to this path.
  25385. */
  25386. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25387. const x0 = this.currentPoint.x;
  25388. const y0 = this.currentPoint.y;
  25389. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25390. return this;
  25391. }
  25392. /**
  25393. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25394. *
  25395. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25396. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25397. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25398. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25399. * @param {number} [aStartAngle=0] - The start angle in radians.
  25400. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25401. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25402. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25403. * @return {Path} A reference to this path.
  25404. */
  25405. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25406. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25407. if ( this.curves.length > 0 ) {
  25408. // if a previous curve is present, attempt to join
  25409. const firstPoint = curve.getPoint( 0 );
  25410. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25411. this.lineTo( firstPoint.x, firstPoint.y );
  25412. }
  25413. }
  25414. this.curves.push( curve );
  25415. const lastPoint = curve.getPoint( 1 );
  25416. this.currentPoint.copy( lastPoint );
  25417. return this;
  25418. }
  25419. copy( source ) {
  25420. super.copy( source );
  25421. this.currentPoint.copy( source.currentPoint );
  25422. return this;
  25423. }
  25424. toJSON() {
  25425. const data = super.toJSON();
  25426. data.currentPoint = this.currentPoint.toArray();
  25427. return data;
  25428. }
  25429. fromJSON( json ) {
  25430. super.fromJSON( json );
  25431. this.currentPoint.fromArray( json.currentPoint );
  25432. return this;
  25433. }
  25434. }
  25435. /**
  25436. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25437. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25438. * points, or to get triangulated faces.
  25439. *
  25440. * ```js
  25441. * const heartShape = new THREE.Shape();
  25442. *
  25443. * heartShape.moveTo( 25, 25 );
  25444. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25445. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25446. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25447. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25448. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25449. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25450. *
  25451. * const extrudeSettings = {
  25452. * depth: 8,
  25453. * bevelEnabled: true,
  25454. * bevelSegments: 2,
  25455. * steps: 2,
  25456. * bevelSize: 1,
  25457. * bevelThickness: 1
  25458. * };
  25459. *
  25460. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25461. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25462. * ```
  25463. *
  25464. * @augments Path
  25465. */
  25466. class Shape extends Path {
  25467. /**
  25468. * Constructs a new shape.
  25469. *
  25470. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25471. */
  25472. constructor( points ) {
  25473. super( points );
  25474. /**
  25475. * The UUID of the shape.
  25476. *
  25477. * @type {string}
  25478. * @readonly
  25479. */
  25480. this.uuid = generateUUID();
  25481. this.type = 'Shape';
  25482. /**
  25483. * Defines the holes in the shape. Hole definitions must use the
  25484. * opposite winding order (CW/CCW) than the outer shape.
  25485. *
  25486. * @type {Array<Path>}
  25487. * @readonly
  25488. */
  25489. this.holes = [];
  25490. }
  25491. /**
  25492. * Returns an array representing each contour of the holes
  25493. * as a list of 2D points.
  25494. *
  25495. * @param {number} divisions - The fineness of the result.
  25496. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25497. */
  25498. getPointsHoles( divisions ) {
  25499. const holesPts = [];
  25500. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25501. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25502. }
  25503. return holesPts;
  25504. }
  25505. // get points of shape and holes (keypoints based on segments parameter)
  25506. /**
  25507. * Returns an object that holds contour data for the shape and its holes as
  25508. * arrays of 2D points.
  25509. *
  25510. * @param {number} divisions - The fineness of the result.
  25511. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25512. */
  25513. extractPoints( divisions ) {
  25514. return {
  25515. shape: this.getPoints( divisions ),
  25516. holes: this.getPointsHoles( divisions )
  25517. };
  25518. }
  25519. copy( source ) {
  25520. super.copy( source );
  25521. this.holes = [];
  25522. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25523. const hole = source.holes[ i ];
  25524. this.holes.push( hole.clone() );
  25525. }
  25526. return this;
  25527. }
  25528. toJSON() {
  25529. const data = super.toJSON();
  25530. data.uuid = this.uuid;
  25531. data.holes = [];
  25532. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25533. const hole = this.holes[ i ];
  25534. data.holes.push( hole.toJSON() );
  25535. }
  25536. return data;
  25537. }
  25538. fromJSON( json ) {
  25539. super.fromJSON( json );
  25540. this.uuid = json.uuid;
  25541. this.holes = [];
  25542. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25543. const hole = json.holes[ i ];
  25544. this.holes.push( new Path().fromJSON( hole ) );
  25545. }
  25546. return this;
  25547. }
  25548. }
  25549. /* eslint-disable */
  25550. // copy of mapbox/earcut version 3.0.2
  25551. // https://github.com/mapbox/earcut/tree/v3.0.2
  25552. function earcut(data, holeIndices, dim = 2) {
  25553. const hasHoles = holeIndices && holeIndices.length;
  25554. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25555. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25556. const triangles = [];
  25557. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25558. let minX, minY, invSize;
  25559. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25560. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25561. if (data.length > 80 * dim) {
  25562. minX = data[0];
  25563. minY = data[1];
  25564. let maxX = minX;
  25565. let maxY = minY;
  25566. for (let i = dim; i < outerLen; i += dim) {
  25567. const x = data[i];
  25568. const y = data[i + 1];
  25569. if (x < minX) minX = x;
  25570. if (y < minY) minY = y;
  25571. if (x > maxX) maxX = x;
  25572. if (y > maxY) maxY = y;
  25573. }
  25574. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25575. invSize = Math.max(maxX - minX, maxY - minY);
  25576. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25577. }
  25578. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25579. return triangles;
  25580. }
  25581. // create a circular doubly linked list from polygon points in the specified winding order
  25582. function linkedList(data, start, end, dim, clockwise) {
  25583. let last;
  25584. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25585. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25586. } else {
  25587. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25588. }
  25589. if (last && equals(last, last.next)) {
  25590. removeNode(last);
  25591. last = last.next;
  25592. }
  25593. return last;
  25594. }
  25595. // eliminate colinear or duplicate points
  25596. function filterPoints(start, end) {
  25597. if (!start) return start;
  25598. if (!end) end = start;
  25599. let p = start,
  25600. again;
  25601. do {
  25602. again = false;
  25603. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25604. removeNode(p);
  25605. p = end = p.prev;
  25606. if (p === p.next) break;
  25607. again = true;
  25608. } else {
  25609. p = p.next;
  25610. }
  25611. } while (again || p !== end);
  25612. return end;
  25613. }
  25614. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25615. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25616. if (!ear) return;
  25617. // interlink polygon nodes in z-order
  25618. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25619. let stop = ear;
  25620. // iterate through ears, slicing them one by one
  25621. while (ear.prev !== ear.next) {
  25622. const prev = ear.prev;
  25623. const next = ear.next;
  25624. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25625. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25626. removeNode(ear);
  25627. // skipping the next vertex leads to less sliver triangles
  25628. ear = next.next;
  25629. stop = next.next;
  25630. continue;
  25631. }
  25632. ear = next;
  25633. // if we looped through the whole remaining polygon and can't find any more ears
  25634. if (ear === stop) {
  25635. // try filtering points and slicing again
  25636. if (!pass) {
  25637. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25638. // if this didn't work, try curing all small self-intersections locally
  25639. } else if (pass === 1) {
  25640. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25641. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25642. // as a last resort, try splitting the remaining polygon into two
  25643. } else if (pass === 2) {
  25644. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25645. }
  25646. break;
  25647. }
  25648. }
  25649. }
  25650. // check whether a polygon node forms a valid ear with adjacent nodes
  25651. function isEar(ear) {
  25652. const a = ear.prev,
  25653. b = ear,
  25654. c = ear.next;
  25655. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25656. // now make sure we don't have other points inside the potential ear
  25657. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25658. // triangle bbox
  25659. const x0 = Math.min(ax, bx, cx),
  25660. y0 = Math.min(ay, by, cy),
  25661. x1 = Math.max(ax, bx, cx),
  25662. y1 = Math.max(ay, by, cy);
  25663. let p = c.next;
  25664. while (p !== a) {
  25665. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25666. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25667. area(p.prev, p, p.next) >= 0) return false;
  25668. p = p.next;
  25669. }
  25670. return true;
  25671. }
  25672. function isEarHashed(ear, minX, minY, invSize) {
  25673. const a = ear.prev,
  25674. b = ear,
  25675. c = ear.next;
  25676. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25677. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25678. // triangle bbox
  25679. const x0 = Math.min(ax, bx, cx),
  25680. y0 = Math.min(ay, by, cy),
  25681. x1 = Math.max(ax, bx, cx),
  25682. y1 = Math.max(ay, by, cy);
  25683. // z-order range for the current triangle bbox;
  25684. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25685. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25686. let p = ear.prevZ,
  25687. n = ear.nextZ;
  25688. // look for points inside the triangle in both directions
  25689. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25690. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25691. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25692. p = p.prevZ;
  25693. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25694. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25695. n = n.nextZ;
  25696. }
  25697. // look for remaining points in decreasing z-order
  25698. while (p && p.z >= minZ) {
  25699. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25700. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25701. p = p.prevZ;
  25702. }
  25703. // look for remaining points in increasing z-order
  25704. while (n && n.z <= maxZ) {
  25705. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25706. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25707. n = n.nextZ;
  25708. }
  25709. return true;
  25710. }
  25711. // go through all polygon nodes and cure small local self-intersections
  25712. function cureLocalIntersections(start, triangles) {
  25713. let p = start;
  25714. do {
  25715. const a = p.prev,
  25716. b = p.next.next;
  25717. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25718. triangles.push(a.i, p.i, b.i);
  25719. // remove two nodes involved
  25720. removeNode(p);
  25721. removeNode(p.next);
  25722. p = start = b;
  25723. }
  25724. p = p.next;
  25725. } while (p !== start);
  25726. return filterPoints(p);
  25727. }
  25728. // try splitting polygon into two and triangulate them independently
  25729. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25730. // look for a valid diagonal that divides the polygon into two
  25731. let a = start;
  25732. do {
  25733. let b = a.next.next;
  25734. while (b !== a.prev) {
  25735. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25736. // split the polygon in two by the diagonal
  25737. let c = splitPolygon(a, b);
  25738. // filter colinear points around the cuts
  25739. a = filterPoints(a, a.next);
  25740. c = filterPoints(c, c.next);
  25741. // run earcut on each half
  25742. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25743. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25744. return;
  25745. }
  25746. b = b.next;
  25747. }
  25748. a = a.next;
  25749. } while (a !== start);
  25750. }
  25751. // link every hole into the outer loop, producing a single-ring polygon without holes
  25752. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25753. const queue = [];
  25754. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25755. const start = holeIndices[i] * dim;
  25756. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25757. const list = linkedList(data, start, end, dim, false);
  25758. if (list === list.next) list.steiner = true;
  25759. queue.push(getLeftmost(list));
  25760. }
  25761. queue.sort(compareXYSlope);
  25762. // process holes from left to right
  25763. for (let i = 0; i < queue.length; i++) {
  25764. outerNode = eliminateHole(queue[i], outerNode);
  25765. }
  25766. return outerNode;
  25767. }
  25768. function compareXYSlope(a, b) {
  25769. let result = a.x - b.x;
  25770. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25771. // the bridge to the outer shell is always the point that they meet at.
  25772. if (result === 0) {
  25773. result = a.y - b.y;
  25774. if (result === 0) {
  25775. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25776. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25777. result = aSlope - bSlope;
  25778. }
  25779. }
  25780. return result;
  25781. }
  25782. // find a bridge between vertices that connects hole with an outer ring and link it
  25783. function eliminateHole(hole, outerNode) {
  25784. const bridge = findHoleBridge(hole, outerNode);
  25785. if (!bridge) {
  25786. return outerNode;
  25787. }
  25788. const bridgeReverse = splitPolygon(bridge, hole);
  25789. // filter collinear points around the cuts
  25790. filterPoints(bridgeReverse, bridgeReverse.next);
  25791. return filterPoints(bridge, bridge.next);
  25792. }
  25793. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25794. function findHoleBridge(hole, outerNode) {
  25795. let p = outerNode;
  25796. const hx = hole.x;
  25797. const hy = hole.y;
  25798. let qx = -Infinity;
  25799. let m;
  25800. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25801. // segment's endpoint with lesser x will be potential connection point
  25802. // unless they intersect at a vertex, then choose the vertex
  25803. if (equals(hole, p)) return p;
  25804. do {
  25805. if (equals(hole, p.next)) return p.next;
  25806. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25807. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25808. if (x <= hx && x > qx) {
  25809. qx = x;
  25810. m = p.x < p.next.x ? p : p.next;
  25811. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25812. }
  25813. }
  25814. p = p.next;
  25815. } while (p !== outerNode);
  25816. if (!m) return null;
  25817. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25818. // if there are no points found, we have a valid connection;
  25819. // otherwise choose the point of the minimum angle with the ray as connection point
  25820. const stop = m;
  25821. const mx = m.x;
  25822. const my = m.y;
  25823. let tanMin = Infinity;
  25824. p = m;
  25825. do {
  25826. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25827. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25828. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25829. if (locallyInside(p, hole) &&
  25830. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25831. m = p;
  25832. tanMin = tan;
  25833. }
  25834. }
  25835. p = p.next;
  25836. } while (p !== stop);
  25837. return m;
  25838. }
  25839. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25840. function sectorContainsSector(m, p) {
  25841. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25842. }
  25843. // interlink polygon nodes in z-order
  25844. function indexCurve(start, minX, minY, invSize) {
  25845. let p = start;
  25846. do {
  25847. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25848. p.prevZ = p.prev;
  25849. p.nextZ = p.next;
  25850. p = p.next;
  25851. } while (p !== start);
  25852. p.prevZ.nextZ = null;
  25853. p.prevZ = null;
  25854. sortLinked(p);
  25855. }
  25856. // Simon Tatham's linked list merge sort algorithm
  25857. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25858. function sortLinked(list) {
  25859. let numMerges;
  25860. let inSize = 1;
  25861. do {
  25862. let p = list;
  25863. let e;
  25864. list = null;
  25865. let tail = null;
  25866. numMerges = 0;
  25867. while (p) {
  25868. numMerges++;
  25869. let q = p;
  25870. let pSize = 0;
  25871. for (let i = 0; i < inSize; i++) {
  25872. pSize++;
  25873. q = q.nextZ;
  25874. if (!q) break;
  25875. }
  25876. let qSize = inSize;
  25877. while (pSize > 0 || (qSize > 0 && q)) {
  25878. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25879. e = p;
  25880. p = p.nextZ;
  25881. pSize--;
  25882. } else {
  25883. e = q;
  25884. q = q.nextZ;
  25885. qSize--;
  25886. }
  25887. if (tail) tail.nextZ = e;
  25888. else list = e;
  25889. e.prevZ = tail;
  25890. tail = e;
  25891. }
  25892. p = q;
  25893. }
  25894. tail.nextZ = null;
  25895. inSize *= 2;
  25896. } while (numMerges > 1);
  25897. return list;
  25898. }
  25899. // z-order of a point given coords and inverse of the longer side of data bbox
  25900. function zOrder(x, y, minX, minY, invSize) {
  25901. // coords are transformed into non-negative 15-bit integer range
  25902. x = (x - minX) * invSize | 0;
  25903. y = (y - minY) * invSize | 0;
  25904. x = (x | (x << 8)) & 0x00FF00FF;
  25905. x = (x | (x << 4)) & 0x0F0F0F0F;
  25906. x = (x | (x << 2)) & 0x33333333;
  25907. x = (x | (x << 1)) & 0x55555555;
  25908. y = (y | (y << 8)) & 0x00FF00FF;
  25909. y = (y | (y << 4)) & 0x0F0F0F0F;
  25910. y = (y | (y << 2)) & 0x33333333;
  25911. y = (y | (y << 1)) & 0x55555555;
  25912. return x | (y << 1);
  25913. }
  25914. // find the leftmost node of a polygon ring
  25915. function getLeftmost(start) {
  25916. let p = start,
  25917. leftmost = start;
  25918. do {
  25919. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25920. p = p.next;
  25921. } while (p !== start);
  25922. return leftmost;
  25923. }
  25924. // check if a point lies within a convex triangle
  25925. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25926. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25927. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25928. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25929. }
  25930. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25931. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25932. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25933. }
  25934. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25935. function isValidDiagonal(a, b) {
  25936. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25937. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25938. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25939. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25940. }
  25941. // signed area of a triangle
  25942. function area(p, q, r) {
  25943. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25944. }
  25945. // check if two points are equal
  25946. function equals(p1, p2) {
  25947. return p1.x === p2.x && p1.y === p2.y;
  25948. }
  25949. // check if two segments intersect
  25950. function intersects(p1, q1, p2, q2) {
  25951. const o1 = sign(area(p1, q1, p2));
  25952. const o2 = sign(area(p1, q1, q2));
  25953. const o3 = sign(area(p2, q2, p1));
  25954. const o4 = sign(area(p2, q2, q1));
  25955. if (o1 !== o2 && o3 !== o4) return true; // general case
  25956. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25957. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25958. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25959. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25960. return false;
  25961. }
  25962. // for collinear points p, q, r, check if point q lies on segment pr
  25963. function onSegment(p, q, r) {
  25964. 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);
  25965. }
  25966. function sign(num) {
  25967. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25968. }
  25969. // check if a polygon diagonal intersects any polygon segments
  25970. function intersectsPolygon(a, b) {
  25971. let p = a;
  25972. do {
  25973. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25974. intersects(p, p.next, a, b)) return true;
  25975. p = p.next;
  25976. } while (p !== a);
  25977. return false;
  25978. }
  25979. // check if a polygon diagonal is locally inside the polygon
  25980. function locallyInside(a, b) {
  25981. return area(a.prev, a, a.next) < 0 ?
  25982. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25983. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25984. }
  25985. // check if the middle point of a polygon diagonal is inside the polygon
  25986. function middleInside(a, b) {
  25987. let p = a;
  25988. let inside = false;
  25989. const px = (a.x + b.x) / 2;
  25990. const py = (a.y + b.y) / 2;
  25991. do {
  25992. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25993. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25994. inside = !inside;
  25995. p = p.next;
  25996. } while (p !== a);
  25997. return inside;
  25998. }
  25999. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  26000. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  26001. function splitPolygon(a, b) {
  26002. const a2 = createNode(a.i, a.x, a.y),
  26003. b2 = createNode(b.i, b.x, b.y),
  26004. an = a.next,
  26005. bp = b.prev;
  26006. a.next = b;
  26007. b.prev = a;
  26008. a2.next = an;
  26009. an.prev = a2;
  26010. b2.next = a2;
  26011. a2.prev = b2;
  26012. bp.next = b2;
  26013. b2.prev = bp;
  26014. return b2;
  26015. }
  26016. // create a node and optionally link it with previous one (in a circular doubly linked list)
  26017. function insertNode(i, x, y, last) {
  26018. const p = createNode(i, x, y);
  26019. if (!last) {
  26020. p.prev = p;
  26021. p.next = p;
  26022. } else {
  26023. p.next = last.next;
  26024. p.prev = last;
  26025. last.next.prev = p;
  26026. last.next = p;
  26027. }
  26028. return p;
  26029. }
  26030. function removeNode(p) {
  26031. p.next.prev = p.prev;
  26032. p.prev.next = p.next;
  26033. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  26034. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  26035. }
  26036. function createNode(i, x, y) {
  26037. return {
  26038. i, // vertex index in coordinates array
  26039. x, y, // vertex coordinates
  26040. prev: null, // previous and next vertex nodes in a polygon ring
  26041. next: null,
  26042. z: 0, // z-order curve value
  26043. prevZ: null, // previous and next nodes in z-order
  26044. nextZ: null,
  26045. steiner: false // indicates whether this is a steiner point
  26046. };
  26047. }
  26048. function signedArea(data, start, end, dim) {
  26049. let sum = 0;
  26050. for (let i = start, j = end - dim; i < end; i += dim) {
  26051. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  26052. j = i;
  26053. }
  26054. return sum;
  26055. }
  26056. /**
  26057. * An implementation of the earcut polygon triangulation algorithm.
  26058. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  26059. *
  26060. * @see https://github.com/mapbox/earcut
  26061. */
  26062. class Earcut {
  26063. /**
  26064. * Triangulates the given shape definition by returning an array of triangles.
  26065. *
  26066. * @param {Array<number>} data - An array with 2D points.
  26067. * @param {Array<number>} holeIndices - An array with indices defining holes.
  26068. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  26069. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  26070. * representing vertex indices.
  26071. */
  26072. static triangulate( data, holeIndices, dim = 2 ) {
  26073. return earcut( data, holeIndices, dim );
  26074. }
  26075. }
  26076. /**
  26077. * A class containing utility functions for shapes.
  26078. *
  26079. * @hideconstructor
  26080. */
  26081. class ShapeUtils {
  26082. /**
  26083. * Calculate area of a ( 2D ) contour polygon.
  26084. *
  26085. * @param {Array<Vector2>} contour - An array of 2D points.
  26086. * @return {number} The area.
  26087. */
  26088. static area( contour ) {
  26089. const n = contour.length;
  26090. let a = 0.0;
  26091. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  26092. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  26093. }
  26094. return a * 0.5;
  26095. }
  26096. /**
  26097. * Returns `true` if the given contour uses a clockwise winding order.
  26098. *
  26099. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  26100. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  26101. */
  26102. static isClockWise( pts ) {
  26103. return ShapeUtils.area( pts ) < 0;
  26104. }
  26105. /**
  26106. * Triangulates the given shape definition.
  26107. *
  26108. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  26109. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  26110. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  26111. */
  26112. static triangulateShape( contour, holes ) {
  26113. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  26114. const holeIndices = []; // array of hole indices
  26115. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  26116. removeDupEndPts( contour );
  26117. addContour( vertices, contour );
  26118. //
  26119. let holeIndex = contour.length;
  26120. holes.forEach( removeDupEndPts );
  26121. for ( let i = 0; i < holes.length; i ++ ) {
  26122. holeIndices.push( holeIndex );
  26123. holeIndex += holes[ i ].length;
  26124. addContour( vertices, holes[ i ] );
  26125. }
  26126. //
  26127. const triangles = Earcut.triangulate( vertices, holeIndices );
  26128. //
  26129. for ( let i = 0; i < triangles.length; i += 3 ) {
  26130. faces.push( triangles.slice( i, i + 3 ) );
  26131. }
  26132. return faces;
  26133. }
  26134. }
  26135. function removeDupEndPts( points ) {
  26136. const l = points.length;
  26137. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  26138. points.pop();
  26139. }
  26140. }
  26141. function addContour( vertices, contour ) {
  26142. for ( let i = 0; i < contour.length; i ++ ) {
  26143. vertices.push( contour[ i ].x );
  26144. vertices.push( contour[ i ].y );
  26145. }
  26146. }
  26147. /**
  26148. * Creates extruded geometry from a path shape.
  26149. *
  26150. * ```js
  26151. * const length = 12, width = 8;
  26152. *
  26153. * const shape = new THREE.Shape();
  26154. * shape.moveTo( 0,0 );
  26155. * shape.lineTo( 0, width );
  26156. * shape.lineTo( length, width );
  26157. * shape.lineTo( length, 0 );
  26158. * shape.lineTo( 0, 0 );
  26159. *
  26160. * const geometry = new THREE.ExtrudeGeometry( shape );
  26161. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26162. * const mesh = new THREE.Mesh( geometry, material ) ;
  26163. * scene.add( mesh );
  26164. * ```
  26165. *
  26166. * @augments BufferGeometry
  26167. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  26168. */
  26169. class ExtrudeGeometry extends BufferGeometry {
  26170. /**
  26171. * Constructs a new extrude geometry.
  26172. *
  26173. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26174. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  26175. */
  26176. 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 = {} ) {
  26177. super();
  26178. this.type = 'ExtrudeGeometry';
  26179. /**
  26180. * Holds the constructor parameters that have been
  26181. * used to generate the geometry. Any modification
  26182. * after instantiation does not change the geometry.
  26183. *
  26184. * @type {Object}
  26185. */
  26186. this.parameters = {
  26187. shapes: shapes,
  26188. options: options
  26189. };
  26190. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  26191. const scope = this;
  26192. const verticesArray = [];
  26193. const uvArray = [];
  26194. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26195. const shape = shapes[ i ];
  26196. addShape( shape );
  26197. }
  26198. // build geometry
  26199. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  26200. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  26201. this.computeVertexNormals();
  26202. // functions
  26203. function addShape( shape ) {
  26204. const placeholder = [];
  26205. // options
  26206. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  26207. const steps = options.steps !== undefined ? options.steps : 1;
  26208. const depth = options.depth !== undefined ? options.depth : 1;
  26209. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  26210. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  26211. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  26212. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  26213. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  26214. const extrudePath = options.extrudePath;
  26215. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  26216. //
  26217. let extrudePts, extrudeByPath = false;
  26218. let splineTube, binormal, normal, position2;
  26219. if ( extrudePath ) {
  26220. extrudePts = extrudePath.getSpacedPoints( steps );
  26221. extrudeByPath = true;
  26222. bevelEnabled = false; // bevels not supported for path extrusion
  26223. // SETUP TNB variables
  26224. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26225. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26226. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26227. binormal = new Vector3();
  26228. normal = new Vector3();
  26229. position2 = new Vector3();
  26230. }
  26231. // Safeguards if bevels are not enabled
  26232. if ( ! bevelEnabled ) {
  26233. bevelSegments = 0;
  26234. bevelThickness = 0;
  26235. bevelSize = 0;
  26236. bevelOffset = 0;
  26237. }
  26238. // Variables initialization
  26239. const shapePoints = shape.extractPoints( curveSegments );
  26240. let vertices = shapePoints.shape;
  26241. const holes = shapePoints.holes;
  26242. const reverse = ! ShapeUtils.isClockWise( vertices );
  26243. if ( reverse ) {
  26244. vertices = vertices.reverse();
  26245. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26246. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26247. const ahole = holes[ h ];
  26248. if ( ShapeUtils.isClockWise( ahole ) ) {
  26249. holes[ h ] = ahole.reverse();
  26250. }
  26251. }
  26252. }
  26253. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  26254. * @param {Array<Vector2>} points
  26255. */
  26256. function mergeOverlappingPoints( points ) {
  26257. const THRESHOLD = 1e-10;
  26258. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26259. let prevPos = points[ 0 ];
  26260. for ( let i = 1; i <= points.length; i ++ ) {
  26261. const currentIndex = i % points.length;
  26262. const currentPos = points[ currentIndex ];
  26263. const dx = currentPos.x - prevPos.x;
  26264. const dy = currentPos.y - prevPos.y;
  26265. const distSq = dx * dx + dy * dy;
  26266. const scalingFactorSqrt = Math.max(
  26267. Math.abs( currentPos.x ),
  26268. Math.abs( currentPos.y ),
  26269. Math.abs( prevPos.x ),
  26270. Math.abs( prevPos.y )
  26271. );
  26272. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26273. if ( distSq <= thresholdSqScaled ) {
  26274. points.splice( currentIndex, 1 );
  26275. i --;
  26276. continue;
  26277. }
  26278. prevPos = currentPos;
  26279. }
  26280. }
  26281. mergeOverlappingPoints( vertices );
  26282. holes.forEach( mergeOverlappingPoints );
  26283. const numHoles = holes.length;
  26284. /* Vertices */
  26285. const contour = vertices; // vertices has all points but contour has only points of circumference
  26286. for ( let h = 0; h < numHoles; h ++ ) {
  26287. const ahole = holes[ h ];
  26288. vertices = vertices.concat( ahole );
  26289. }
  26290. function scalePt2( pt, vec, size ) {
  26291. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26292. return pt.clone().addScaledVector( vec, size );
  26293. }
  26294. const vlen = vertices.length;
  26295. // Find directions for point movement
  26296. function getBevelVec( inPt, inPrev, inNext ) {
  26297. // computes for inPt the corresponding point inPt' on a new contour
  26298. // shifted by 1 unit (length of normalized vector) to the left
  26299. // if we walk along contour clockwise, this new contour is outside the old one
  26300. //
  26301. // inPt' is the intersection of the two lines parallel to the two
  26302. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26303. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26304. // good reading for geometry algorithms (here: line-line intersection)
  26305. // http://geomalgorithms.com/a05-_intersect-1.html
  26306. const v_prev_x = inPt.x - inPrev.x,
  26307. v_prev_y = inPt.y - inPrev.y;
  26308. const v_next_x = inNext.x - inPt.x,
  26309. v_next_y = inNext.y - inPt.y;
  26310. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26311. // check for collinear edges
  26312. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26313. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26314. // not collinear
  26315. // length of vectors for normalizing
  26316. const v_prev_len = Math.sqrt( v_prev_lensq );
  26317. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26318. // shift adjacent points by unit vectors to the left
  26319. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26320. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26321. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26322. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26323. // scaling factor for v_prev to intersection point
  26324. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26325. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26326. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26327. // vector from inPt to intersection point
  26328. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26329. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26330. // Don't normalize!, otherwise sharp corners become ugly
  26331. // but prevent crazy spikes
  26332. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26333. if ( v_trans_lensq <= 2 ) {
  26334. return new Vector2( v_trans_x, v_trans_y );
  26335. } else {
  26336. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26337. }
  26338. } else {
  26339. // handle special case of collinear edges
  26340. let direction_eq = false; // assumes: opposite
  26341. if ( v_prev_x > Number.EPSILON ) {
  26342. if ( v_next_x > Number.EPSILON ) {
  26343. direction_eq = true;
  26344. }
  26345. } else {
  26346. if ( v_prev_x < - Number.EPSILON ) {
  26347. if ( v_next_x < - Number.EPSILON ) {
  26348. direction_eq = true;
  26349. }
  26350. } else {
  26351. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26352. direction_eq = true;
  26353. }
  26354. }
  26355. }
  26356. if ( direction_eq ) {
  26357. // log("Warning: lines are a straight sequence");
  26358. v_trans_x = - v_prev_y;
  26359. v_trans_y = v_prev_x;
  26360. shrink_by = Math.sqrt( v_prev_lensq );
  26361. } else {
  26362. // log("Warning: lines are a straight spike");
  26363. v_trans_x = v_prev_x;
  26364. v_trans_y = v_prev_y;
  26365. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26366. }
  26367. }
  26368. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26369. }
  26370. const contourMovements = [];
  26371. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26372. if ( j === il ) j = 0;
  26373. if ( k === il ) k = 0;
  26374. // (j)---(i)---(k)
  26375. // log('i,j,k', i, j , k)
  26376. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26377. }
  26378. const holesMovements = [];
  26379. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26380. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26381. const ahole = holes[ h ];
  26382. oneHoleMovements = [];
  26383. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26384. if ( j === il ) j = 0;
  26385. if ( k === il ) k = 0;
  26386. // (j)---(i)---(k)
  26387. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26388. }
  26389. holesMovements.push( oneHoleMovements );
  26390. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26391. }
  26392. let faces;
  26393. if ( bevelSegments === 0 ) {
  26394. faces = ShapeUtils.triangulateShape( contour, holes );
  26395. } else {
  26396. const contractedContourVertices = [];
  26397. const expandedHoleVertices = [];
  26398. // Loop bevelSegments, 1 for the front, 1 for the back
  26399. for ( let b = 0; b < bevelSegments; b ++ ) {
  26400. //for ( b = bevelSegments; b > 0; b -- ) {
  26401. const t = b / bevelSegments;
  26402. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26403. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26404. // contract shape
  26405. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26406. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26407. v( vert.x, vert.y, - z );
  26408. if ( t === 0 ) contractedContourVertices.push( vert );
  26409. }
  26410. // expand holes
  26411. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26412. const ahole = holes[ h ];
  26413. oneHoleMovements = holesMovements[ h ];
  26414. const oneHoleVertices = [];
  26415. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26416. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26417. v( vert.x, vert.y, - z );
  26418. if ( t === 0 ) oneHoleVertices.push( vert );
  26419. }
  26420. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26421. }
  26422. }
  26423. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26424. }
  26425. const flen = faces.length;
  26426. const bs = bevelSize + bevelOffset;
  26427. // Back facing vertices
  26428. for ( let i = 0; i < vlen; i ++ ) {
  26429. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26430. if ( ! extrudeByPath ) {
  26431. v( vert.x, vert.y, 0 );
  26432. } else {
  26433. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26434. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26435. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26436. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26437. v( position2.x, position2.y, position2.z );
  26438. }
  26439. }
  26440. // Add stepped vertices...
  26441. // Including front facing vertices
  26442. for ( let s = 1; s <= steps; s ++ ) {
  26443. for ( let i = 0; i < vlen; i ++ ) {
  26444. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26445. if ( ! extrudeByPath ) {
  26446. v( vert.x, vert.y, depth / steps * s );
  26447. } else {
  26448. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26449. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26450. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26451. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26452. v( position2.x, position2.y, position2.z );
  26453. }
  26454. }
  26455. }
  26456. // Add bevel segments planes
  26457. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26458. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26459. const t = b / bevelSegments;
  26460. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26461. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26462. // contract shape
  26463. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26464. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26465. v( vert.x, vert.y, depth + z );
  26466. }
  26467. // expand holes
  26468. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26469. const ahole = holes[ h ];
  26470. oneHoleMovements = holesMovements[ h ];
  26471. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26472. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26473. if ( ! extrudeByPath ) {
  26474. v( vert.x, vert.y, depth + z );
  26475. } else {
  26476. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26477. }
  26478. }
  26479. }
  26480. }
  26481. /* Faces */
  26482. // Top and bottom faces
  26483. buildLidFaces();
  26484. // Sides faces
  26485. buildSideFaces();
  26486. ///// Internal functions
  26487. function buildLidFaces() {
  26488. const start = verticesArray.length / 3;
  26489. if ( bevelEnabled ) {
  26490. let layer = 0; // steps + 1
  26491. let offset = vlen * layer;
  26492. // Bottom faces
  26493. for ( let i = 0; i < flen; i ++ ) {
  26494. const face = faces[ i ];
  26495. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26496. }
  26497. layer = steps + bevelSegments * 2;
  26498. offset = vlen * layer;
  26499. // Top faces
  26500. for ( let i = 0; i < flen; i ++ ) {
  26501. const face = faces[ i ];
  26502. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26503. }
  26504. } else {
  26505. // Bottom faces
  26506. for ( let i = 0; i < flen; i ++ ) {
  26507. const face = faces[ i ];
  26508. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26509. }
  26510. // Top faces
  26511. for ( let i = 0; i < flen; i ++ ) {
  26512. const face = faces[ i ];
  26513. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26514. }
  26515. }
  26516. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26517. }
  26518. // Create faces for the z-sides of the shape
  26519. function buildSideFaces() {
  26520. const start = verticesArray.length / 3;
  26521. let layeroffset = 0;
  26522. sidewalls( contour, layeroffset );
  26523. layeroffset += contour.length;
  26524. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26525. const ahole = holes[ h ];
  26526. sidewalls( ahole, layeroffset );
  26527. //, true
  26528. layeroffset += ahole.length;
  26529. }
  26530. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26531. }
  26532. function sidewalls( contour, layeroffset ) {
  26533. let i = contour.length;
  26534. while ( -- i >= 0 ) {
  26535. const j = i;
  26536. let k = i - 1;
  26537. if ( k < 0 ) k = contour.length - 1;
  26538. //log('b', i,j, i-1, k,vertices.length);
  26539. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26540. const slen1 = vlen * s;
  26541. const slen2 = vlen * ( s + 1 );
  26542. const a = layeroffset + j + slen1,
  26543. b = layeroffset + k + slen1,
  26544. c = layeroffset + k + slen2,
  26545. d = layeroffset + j + slen2;
  26546. f4( a, b, c, d );
  26547. }
  26548. }
  26549. }
  26550. function v( x, y, z ) {
  26551. placeholder.push( x );
  26552. placeholder.push( y );
  26553. placeholder.push( z );
  26554. }
  26555. function f3( a, b, c ) {
  26556. addVertex( a );
  26557. addVertex( b );
  26558. addVertex( c );
  26559. const nextIndex = verticesArray.length / 3;
  26560. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26561. addUV( uvs[ 0 ] );
  26562. addUV( uvs[ 1 ] );
  26563. addUV( uvs[ 2 ] );
  26564. }
  26565. function f4( a, b, c, d ) {
  26566. addVertex( a );
  26567. addVertex( b );
  26568. addVertex( d );
  26569. addVertex( b );
  26570. addVertex( c );
  26571. addVertex( d );
  26572. const nextIndex = verticesArray.length / 3;
  26573. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26574. addUV( uvs[ 0 ] );
  26575. addUV( uvs[ 1 ] );
  26576. addUV( uvs[ 3 ] );
  26577. addUV( uvs[ 1 ] );
  26578. addUV( uvs[ 2 ] );
  26579. addUV( uvs[ 3 ] );
  26580. }
  26581. function addVertex( index ) {
  26582. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26583. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26584. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26585. }
  26586. function addUV( vector2 ) {
  26587. uvArray.push( vector2.x );
  26588. uvArray.push( vector2.y );
  26589. }
  26590. }
  26591. }
  26592. copy( source ) {
  26593. super.copy( source );
  26594. this.parameters = Object.assign( {}, source.parameters );
  26595. return this;
  26596. }
  26597. toJSON() {
  26598. const data = super.toJSON();
  26599. const shapes = this.parameters.shapes;
  26600. const options = this.parameters.options;
  26601. return toJSON$1( shapes, options, data );
  26602. }
  26603. /**
  26604. * Factory method for creating an instance of this class from the given
  26605. * JSON object.
  26606. *
  26607. * @param {Object} data - A JSON object representing the serialized geometry.
  26608. * @param {Array<Shape>} shapes - An array of shapes.
  26609. * @return {ExtrudeGeometry} A new instance.
  26610. */
  26611. static fromJSON( data, shapes ) {
  26612. const geometryShapes = [];
  26613. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26614. const shape = shapes[ data.shapes[ j ] ];
  26615. geometryShapes.push( shape );
  26616. }
  26617. const extrudePath = data.options.extrudePath;
  26618. if ( extrudePath !== undefined ) {
  26619. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26620. }
  26621. return new ExtrudeGeometry( geometryShapes, data.options );
  26622. }
  26623. }
  26624. const WorldUVGenerator = {
  26625. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26626. const a_x = vertices[ indexA * 3 ];
  26627. const a_y = vertices[ indexA * 3 + 1 ];
  26628. const b_x = vertices[ indexB * 3 ];
  26629. const b_y = vertices[ indexB * 3 + 1 ];
  26630. const c_x = vertices[ indexC * 3 ];
  26631. const c_y = vertices[ indexC * 3 + 1 ];
  26632. return [
  26633. new Vector2( a_x, a_y ),
  26634. new Vector2( b_x, b_y ),
  26635. new Vector2( c_x, c_y )
  26636. ];
  26637. },
  26638. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26639. const a_x = vertices[ indexA * 3 ];
  26640. const a_y = vertices[ indexA * 3 + 1 ];
  26641. const a_z = vertices[ indexA * 3 + 2 ];
  26642. const b_x = vertices[ indexB * 3 ];
  26643. const b_y = vertices[ indexB * 3 + 1 ];
  26644. const b_z = vertices[ indexB * 3 + 2 ];
  26645. const c_x = vertices[ indexC * 3 ];
  26646. const c_y = vertices[ indexC * 3 + 1 ];
  26647. const c_z = vertices[ indexC * 3 + 2 ];
  26648. const d_x = vertices[ indexD * 3 ];
  26649. const d_y = vertices[ indexD * 3 + 1 ];
  26650. const d_z = vertices[ indexD * 3 + 2 ];
  26651. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26652. return [
  26653. new Vector2( a_x, 1 - a_z ),
  26654. new Vector2( b_x, 1 - b_z ),
  26655. new Vector2( c_x, 1 - c_z ),
  26656. new Vector2( d_x, 1 - d_z )
  26657. ];
  26658. } else {
  26659. return [
  26660. new Vector2( a_y, 1 - a_z ),
  26661. new Vector2( b_y, 1 - b_z ),
  26662. new Vector2( c_y, 1 - c_z ),
  26663. new Vector2( d_y, 1 - d_z )
  26664. ];
  26665. }
  26666. }
  26667. };
  26668. function toJSON$1( shapes, options, data ) {
  26669. data.shapes = [];
  26670. if ( Array.isArray( shapes ) ) {
  26671. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26672. const shape = shapes[ i ];
  26673. data.shapes.push( shape.uuid );
  26674. }
  26675. } else {
  26676. data.shapes.push( shapes.uuid );
  26677. }
  26678. data.options = Object.assign( {}, options );
  26679. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26680. return data;
  26681. }
  26682. /**
  26683. * A geometry class for representing an icosahedron.
  26684. *
  26685. * ```js
  26686. * const geometry = new THREE.IcosahedronGeometry();
  26687. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26688. * const icosahedron = new THREE.Mesh( geometry, material );
  26689. * scene.add( icosahedron );
  26690. * ```
  26691. *
  26692. * @augments PolyhedronGeometry
  26693. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26694. */
  26695. class IcosahedronGeometry extends PolyhedronGeometry {
  26696. /**
  26697. * Constructs a new icosahedron geometry.
  26698. *
  26699. * @param {number} [radius=1] - Radius of the icosahedron.
  26700. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26701. */
  26702. constructor( radius = 1, detail = 0 ) {
  26703. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26704. const vertices = [
  26705. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26706. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26707. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26708. ];
  26709. const indices = [
  26710. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26711. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26712. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26713. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26714. ];
  26715. super( vertices, indices, radius, detail );
  26716. this.type = 'IcosahedronGeometry';
  26717. /**
  26718. * Holds the constructor parameters that have been
  26719. * used to generate the geometry. Any modification
  26720. * after instantiation does not change the geometry.
  26721. *
  26722. * @type {Object}
  26723. */
  26724. this.parameters = {
  26725. radius: radius,
  26726. detail: detail
  26727. };
  26728. }
  26729. /**
  26730. * Factory method for creating an instance of this class from the given
  26731. * JSON object.
  26732. *
  26733. * @param {Object} data - A JSON object representing the serialized geometry.
  26734. * @return {IcosahedronGeometry} A new instance.
  26735. */
  26736. static fromJSON( data ) {
  26737. return new IcosahedronGeometry( data.radius, data.detail );
  26738. }
  26739. }
  26740. /**
  26741. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26742. *
  26743. * ```js
  26744. * const points = [];
  26745. * for ( let i = 0; i < 10; i ++ ) {
  26746. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26747. * }
  26748. * const geometry = new THREE.LatheGeometry( points );
  26749. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26750. * const lathe = new THREE.Mesh( geometry, material );
  26751. * scene.add( lathe );
  26752. * ```
  26753. *
  26754. * @augments BufferGeometry
  26755. * @demo scenes/geometry-browser.html#LatheGeometry
  26756. */
  26757. class LatheGeometry extends BufferGeometry {
  26758. /**
  26759. * Constructs a new lathe geometry.
  26760. *
  26761. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26762. * must be greater than zero.
  26763. * @param {number} [segments=12] - The number of circumference segments to generate.
  26764. * @param {number} [phiStart=0] - The starting angle in radians.
  26765. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26766. * closed lathe, less than 2PI is a portion.
  26767. */
  26768. 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 ) {
  26769. super();
  26770. this.type = 'LatheGeometry';
  26771. /**
  26772. * Holds the constructor parameters that have been
  26773. * used to generate the geometry. Any modification
  26774. * after instantiation does not change the geometry.
  26775. *
  26776. * @type {Object}
  26777. */
  26778. this.parameters = {
  26779. points: points,
  26780. segments: segments,
  26781. phiStart: phiStart,
  26782. phiLength: phiLength
  26783. };
  26784. segments = Math.floor( segments );
  26785. // clamp phiLength so it's in range of [ 0, 2PI ]
  26786. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26787. // buffers
  26788. const indices = [];
  26789. const vertices = [];
  26790. const uvs = [];
  26791. const initNormals = [];
  26792. const normals = [];
  26793. // helper variables
  26794. const inverseSegments = 1.0 / segments;
  26795. const vertex = new Vector3();
  26796. const uv = new Vector2();
  26797. const normal = new Vector3();
  26798. const curNormal = new Vector3();
  26799. const prevNormal = new Vector3();
  26800. let dx = 0;
  26801. let dy = 0;
  26802. // pre-compute normals for initial "meridian"
  26803. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26804. switch ( j ) {
  26805. case 0: // special handling for 1st vertex on path
  26806. dx = points[ j + 1 ].x - points[ j ].x;
  26807. dy = points[ j + 1 ].y - points[ j ].y;
  26808. normal.x = dy * 1.0;
  26809. normal.y = - dx;
  26810. normal.z = dy * 0.0;
  26811. prevNormal.copy( normal );
  26812. normal.normalize();
  26813. initNormals.push( normal.x, normal.y, normal.z );
  26814. break;
  26815. case ( points.length - 1 ): // special handling for last Vertex on path
  26816. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26817. break;
  26818. default: // default handling for all vertices in between
  26819. dx = points[ j + 1 ].x - points[ j ].x;
  26820. dy = points[ j + 1 ].y - points[ j ].y;
  26821. normal.x = dy * 1.0;
  26822. normal.y = - dx;
  26823. normal.z = dy * 0.0;
  26824. curNormal.copy( normal );
  26825. normal.x += prevNormal.x;
  26826. normal.y += prevNormal.y;
  26827. normal.z += prevNormal.z;
  26828. normal.normalize();
  26829. initNormals.push( normal.x, normal.y, normal.z );
  26830. prevNormal.copy( curNormal );
  26831. }
  26832. }
  26833. // generate vertices, uvs and normals
  26834. for ( let i = 0; i <= segments; i ++ ) {
  26835. const phi = phiStart + i * inverseSegments * phiLength;
  26836. const sin = Math.sin( phi );
  26837. const cos = Math.cos( phi );
  26838. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26839. // vertex
  26840. vertex.x = points[ j ].x * sin;
  26841. vertex.y = points[ j ].y;
  26842. vertex.z = points[ j ].x * cos;
  26843. vertices.push( vertex.x, vertex.y, vertex.z );
  26844. // uv
  26845. uv.x = i / segments;
  26846. uv.y = j / ( points.length - 1 );
  26847. uvs.push( uv.x, uv.y );
  26848. // normal
  26849. const x = initNormals[ 3 * j + 0 ] * sin;
  26850. const y = initNormals[ 3 * j + 1 ];
  26851. const z = initNormals[ 3 * j + 0 ] * cos;
  26852. normals.push( x, y, z );
  26853. }
  26854. }
  26855. // indices
  26856. for ( let i = 0; i < segments; i ++ ) {
  26857. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26858. const base = j + i * points.length;
  26859. const a = base;
  26860. const b = base + points.length;
  26861. const c = base + points.length + 1;
  26862. const d = base + 1;
  26863. // faces
  26864. indices.push( a, b, d );
  26865. indices.push( c, d, b );
  26866. }
  26867. }
  26868. // build geometry
  26869. this.setIndex( indices );
  26870. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26871. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26872. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26873. }
  26874. copy( source ) {
  26875. super.copy( source );
  26876. this.parameters = Object.assign( {}, source.parameters );
  26877. return this;
  26878. }
  26879. /**
  26880. * Factory method for creating an instance of this class from the given
  26881. * JSON object.
  26882. *
  26883. * @param {Object} data - A JSON object representing the serialized geometry.
  26884. * @return {LatheGeometry} A new instance.
  26885. */
  26886. static fromJSON( data ) {
  26887. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26888. }
  26889. }
  26890. /**
  26891. * A geometry class for representing an octahedron.
  26892. *
  26893. * ```js
  26894. * const geometry = new THREE.OctahedronGeometry();
  26895. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26896. * const octahedron = new THREE.Mesh( geometry, material );
  26897. * scene.add( octahedron );
  26898. * ```
  26899. *
  26900. * @augments PolyhedronGeometry
  26901. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26902. */
  26903. class OctahedronGeometry extends PolyhedronGeometry {
  26904. /**
  26905. * Constructs a new octahedron geometry.
  26906. *
  26907. * @param {number} [radius=1] - Radius of the octahedron.
  26908. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26909. */
  26910. constructor( radius = 1, detail = 0 ) {
  26911. const vertices = [
  26912. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26913. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26914. ];
  26915. const indices = [
  26916. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26917. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26918. 1, 3, 4, 1, 4, 2
  26919. ];
  26920. super( vertices, indices, radius, detail );
  26921. this.type = 'OctahedronGeometry';
  26922. /**
  26923. * Holds the constructor parameters that have been
  26924. * used to generate the geometry. Any modification
  26925. * after instantiation does not change the geometry.
  26926. *
  26927. * @type {Object}
  26928. */
  26929. this.parameters = {
  26930. radius: radius,
  26931. detail: detail
  26932. };
  26933. }
  26934. /**
  26935. * Factory method for creating an instance of this class from the given
  26936. * JSON object.
  26937. *
  26938. * @param {Object} data - A JSON object representing the serialized geometry.
  26939. * @return {OctahedronGeometry} A new instance.
  26940. */
  26941. static fromJSON( data ) {
  26942. return new OctahedronGeometry( data.radius, data.detail );
  26943. }
  26944. }
  26945. /**
  26946. * A geometry class for representing a plane.
  26947. *
  26948. * ```js
  26949. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26950. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26951. * const plane = new THREE.Mesh( geometry, material );
  26952. * scene.add( plane );
  26953. * ```
  26954. *
  26955. * @augments BufferGeometry
  26956. * @demo scenes/geometry-browser.html#PlaneGeometry
  26957. */
  26958. class PlaneGeometry extends BufferGeometry {
  26959. /**
  26960. * Constructs a new plane geometry.
  26961. *
  26962. * @param {number} [width=1] - The width along the X axis.
  26963. * @param {number} [height=1] - The height along the Y axis
  26964. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26965. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26966. */
  26967. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26968. super();
  26969. this.type = 'PlaneGeometry';
  26970. /**
  26971. * Holds the constructor parameters that have been
  26972. * used to generate the geometry. Any modification
  26973. * after instantiation does not change the geometry.
  26974. *
  26975. * @type {Object}
  26976. */
  26977. this.parameters = {
  26978. width: width,
  26979. height: height,
  26980. widthSegments: widthSegments,
  26981. heightSegments: heightSegments
  26982. };
  26983. const width_half = width / 2;
  26984. const height_half = height / 2;
  26985. const gridX = Math.floor( widthSegments );
  26986. const gridY = Math.floor( heightSegments );
  26987. const gridX1 = gridX + 1;
  26988. const gridY1 = gridY + 1;
  26989. const segment_width = width / gridX;
  26990. const segment_height = height / gridY;
  26991. //
  26992. const indices = [];
  26993. const vertices = [];
  26994. const normals = [];
  26995. const uvs = [];
  26996. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26997. const y = iy * segment_height - height_half;
  26998. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26999. const x = ix * segment_width - width_half;
  27000. vertices.push( x, - y, 0 );
  27001. normals.push( 0, 0, 1 );
  27002. uvs.push( ix / gridX );
  27003. uvs.push( 1 - ( iy / gridY ) );
  27004. }
  27005. }
  27006. for ( let iy = 0; iy < gridY; iy ++ ) {
  27007. for ( let ix = 0; ix < gridX; ix ++ ) {
  27008. const a = ix + gridX1 * iy;
  27009. const b = ix + gridX1 * ( iy + 1 );
  27010. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  27011. const d = ( ix + 1 ) + gridX1 * iy;
  27012. indices.push( a, b, d );
  27013. indices.push( b, c, d );
  27014. }
  27015. }
  27016. this.setIndex( indices );
  27017. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27018. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27019. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27020. }
  27021. copy( source ) {
  27022. super.copy( source );
  27023. this.parameters = Object.assign( {}, source.parameters );
  27024. return this;
  27025. }
  27026. /**
  27027. * Factory method for creating an instance of this class from the given
  27028. * JSON object.
  27029. *
  27030. * @param {Object} data - A JSON object representing the serialized geometry.
  27031. * @return {PlaneGeometry} A new instance.
  27032. */
  27033. static fromJSON( data ) {
  27034. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  27035. }
  27036. }
  27037. /**
  27038. * A class for generating a two-dimensional ring geometry.
  27039. *
  27040. * ```js
  27041. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  27042. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  27043. * const mesh = new THREE.Mesh( geometry, material );
  27044. * scene.add( mesh );
  27045. * ```
  27046. *
  27047. * @augments BufferGeometry
  27048. * @demo scenes/geometry-browser.html#RingGeometry
  27049. */
  27050. class RingGeometry extends BufferGeometry {
  27051. /**
  27052. * Constructs a new ring geometry.
  27053. *
  27054. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  27055. * @param {number} [outerRadius=1] - The outer radius of the ring.
  27056. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  27057. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  27058. * @param {number} [thetaStart=0] - Starting angle in radians.
  27059. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  27060. */
  27061. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27062. super();
  27063. this.type = 'RingGeometry';
  27064. /**
  27065. * Holds the constructor parameters that have been
  27066. * used to generate the geometry. Any modification
  27067. * after instantiation does not change the geometry.
  27068. *
  27069. * @type {Object}
  27070. */
  27071. this.parameters = {
  27072. innerRadius: innerRadius,
  27073. outerRadius: outerRadius,
  27074. thetaSegments: thetaSegments,
  27075. phiSegments: phiSegments,
  27076. thetaStart: thetaStart,
  27077. thetaLength: thetaLength
  27078. };
  27079. thetaSegments = Math.max( 3, thetaSegments );
  27080. phiSegments = Math.max( 1, phiSegments );
  27081. // buffers
  27082. const indices = [];
  27083. const vertices = [];
  27084. const normals = [];
  27085. const uvs = [];
  27086. // some helper variables
  27087. let radius = innerRadius;
  27088. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  27089. const vertex = new Vector3();
  27090. const uv = new Vector2();
  27091. // generate vertices, normals and uvs
  27092. for ( let j = 0; j <= phiSegments; j ++ ) {
  27093. for ( let i = 0; i <= thetaSegments; i ++ ) {
  27094. // values are generate from the inside of the ring to the outside
  27095. const segment = thetaStart + i / thetaSegments * thetaLength;
  27096. // vertex
  27097. vertex.x = radius * Math.cos( segment );
  27098. vertex.y = radius * Math.sin( segment );
  27099. vertices.push( vertex.x, vertex.y, vertex.z );
  27100. // normal
  27101. normals.push( 0, 0, 1 );
  27102. // uv
  27103. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  27104. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  27105. uvs.push( uv.x, uv.y );
  27106. }
  27107. // increase the radius for next row of vertices
  27108. radius += radiusStep;
  27109. }
  27110. // indices
  27111. for ( let j = 0; j < phiSegments; j ++ ) {
  27112. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  27113. for ( let i = 0; i < thetaSegments; i ++ ) {
  27114. const segment = i + thetaSegmentLevel;
  27115. const a = segment;
  27116. const b = segment + thetaSegments + 1;
  27117. const c = segment + thetaSegments + 2;
  27118. const d = segment + 1;
  27119. // faces
  27120. indices.push( a, b, d );
  27121. indices.push( b, c, d );
  27122. }
  27123. }
  27124. // build geometry
  27125. this.setIndex( indices );
  27126. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27127. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27128. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27129. }
  27130. copy( source ) {
  27131. super.copy( source );
  27132. this.parameters = Object.assign( {}, source.parameters );
  27133. return this;
  27134. }
  27135. /**
  27136. * Factory method for creating an instance of this class from the given
  27137. * JSON object.
  27138. *
  27139. * @param {Object} data - A JSON object representing the serialized geometry.
  27140. * @return {RingGeometry} A new instance.
  27141. */
  27142. static fromJSON( data ) {
  27143. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  27144. }
  27145. }
  27146. /**
  27147. * Creates an one-sided polygonal geometry from one or more path shapes.
  27148. *
  27149. * ```js
  27150. * const arcShape = new THREE.Shape()
  27151. * .moveTo( 5, 1 )
  27152. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  27153. *
  27154. * const geometry = new THREE.ShapeGeometry( arcShape );
  27155. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  27156. * const mesh = new THREE.Mesh( geometry, material ) ;
  27157. * scene.add( mesh );
  27158. * ```
  27159. *
  27160. * @augments BufferGeometry
  27161. * @demo scenes/geometry-browser.html#ShapeGeometry
  27162. */
  27163. class ShapeGeometry extends BufferGeometry {
  27164. /**
  27165. * Constructs a new shape geometry.
  27166. *
  27167. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  27168. * @param {number} [curveSegments=12] - Number of segments per shape.
  27169. */
  27170. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  27171. super();
  27172. this.type = 'ShapeGeometry';
  27173. /**
  27174. * Holds the constructor parameters that have been
  27175. * used to generate the geometry. Any modification
  27176. * after instantiation does not change the geometry.
  27177. *
  27178. * @type {Object}
  27179. */
  27180. this.parameters = {
  27181. shapes: shapes,
  27182. curveSegments: curveSegments
  27183. };
  27184. // buffers
  27185. const indices = [];
  27186. const vertices = [];
  27187. const normals = [];
  27188. const uvs = [];
  27189. // helper variables
  27190. let groupStart = 0;
  27191. let groupCount = 0;
  27192. // allow single and array values for "shapes" parameter
  27193. if ( Array.isArray( shapes ) === false ) {
  27194. addShape( shapes );
  27195. } else {
  27196. for ( let i = 0; i < shapes.length; i ++ ) {
  27197. addShape( shapes[ i ] );
  27198. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  27199. groupStart += groupCount;
  27200. groupCount = 0;
  27201. }
  27202. }
  27203. // build geometry
  27204. this.setIndex( indices );
  27205. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27206. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27207. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27208. // helper functions
  27209. function addShape( shape ) {
  27210. const indexOffset = vertices.length / 3;
  27211. const points = shape.extractPoints( curveSegments );
  27212. let shapeVertices = points.shape;
  27213. const shapeHoles = points.holes;
  27214. // check direction of vertices
  27215. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  27216. shapeVertices = shapeVertices.reverse();
  27217. }
  27218. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27219. const shapeHole = shapeHoles[ i ];
  27220. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27221. shapeHoles[ i ] = shapeHole.reverse();
  27222. }
  27223. }
  27224. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27225. // join vertices of inner and outer paths to a single array
  27226. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27227. const shapeHole = shapeHoles[ i ];
  27228. shapeVertices = shapeVertices.concat( shapeHole );
  27229. }
  27230. // vertices, normals, uvs
  27231. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27232. const vertex = shapeVertices[ i ];
  27233. vertices.push( vertex.x, vertex.y, 0 );
  27234. normals.push( 0, 0, 1 );
  27235. uvs.push( vertex.x, vertex.y ); // world uvs
  27236. }
  27237. // indices
  27238. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27239. const face = faces[ i ];
  27240. const a = face[ 0 ] + indexOffset;
  27241. const b = face[ 1 ] + indexOffset;
  27242. const c = face[ 2 ] + indexOffset;
  27243. indices.push( a, b, c );
  27244. groupCount += 3;
  27245. }
  27246. }
  27247. }
  27248. copy( source ) {
  27249. super.copy( source );
  27250. this.parameters = Object.assign( {}, source.parameters );
  27251. return this;
  27252. }
  27253. toJSON() {
  27254. const data = super.toJSON();
  27255. const shapes = this.parameters.shapes;
  27256. return toJSON( shapes, data );
  27257. }
  27258. /**
  27259. * Factory method for creating an instance of this class from the given
  27260. * JSON object.
  27261. *
  27262. * @param {Object} data - A JSON object representing the serialized geometry.
  27263. * @param {Array<Shape>} shapes - An array of shapes.
  27264. * @return {ShapeGeometry} A new instance.
  27265. */
  27266. static fromJSON( data, shapes ) {
  27267. const geometryShapes = [];
  27268. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27269. const shape = shapes[ data.shapes[ j ] ];
  27270. geometryShapes.push( shape );
  27271. }
  27272. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27273. }
  27274. }
  27275. function toJSON( shapes, data ) {
  27276. data.shapes = [];
  27277. if ( Array.isArray( shapes ) ) {
  27278. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27279. const shape = shapes[ i ];
  27280. data.shapes.push( shape.uuid );
  27281. }
  27282. } else {
  27283. data.shapes.push( shapes.uuid );
  27284. }
  27285. return data;
  27286. }
  27287. /**
  27288. * A class for generating a sphere geometry.
  27289. *
  27290. * ```js
  27291. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27292. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27293. * const sphere = new THREE.Mesh( geometry, material );
  27294. * scene.add( sphere );
  27295. * ```
  27296. *
  27297. * @augments BufferGeometry
  27298. * @demo scenes/geometry-browser.html#SphereGeometry
  27299. */
  27300. class SphereGeometry extends BufferGeometry {
  27301. /**
  27302. * Constructs a new sphere geometry.
  27303. *
  27304. * @param {number} [radius=1] - The sphere radius.
  27305. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27306. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27307. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27308. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27309. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27310. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27311. */
  27312. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27313. super();
  27314. this.type = 'SphereGeometry';
  27315. /**
  27316. * Holds the constructor parameters that have been
  27317. * used to generate the geometry. Any modification
  27318. * after instantiation does not change the geometry.
  27319. *
  27320. * @type {Object}
  27321. */
  27322. this.parameters = {
  27323. radius: radius,
  27324. widthSegments: widthSegments,
  27325. heightSegments: heightSegments,
  27326. phiStart: phiStart,
  27327. phiLength: phiLength,
  27328. thetaStart: thetaStart,
  27329. thetaLength: thetaLength
  27330. };
  27331. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27332. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27333. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27334. let index = 0;
  27335. const grid = [];
  27336. const vertex = new Vector3();
  27337. const normal = new Vector3();
  27338. // buffers
  27339. const indices = [];
  27340. const vertices = [];
  27341. const normals = [];
  27342. const uvs = [];
  27343. // generate vertices, normals and uvs
  27344. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27345. const verticesRow = [];
  27346. const v = iy / heightSegments;
  27347. // special case for the poles
  27348. let uOffset = 0;
  27349. if ( iy === 0 && thetaStart === 0 ) {
  27350. uOffset = 0.5 / widthSegments;
  27351. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27352. uOffset = -0.5 / widthSegments;
  27353. }
  27354. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27355. const u = ix / widthSegments;
  27356. // vertex
  27357. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27358. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27359. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27360. vertices.push( vertex.x, vertex.y, vertex.z );
  27361. // normal
  27362. normal.copy( vertex ).normalize();
  27363. normals.push( normal.x, normal.y, normal.z );
  27364. // uv
  27365. uvs.push( u + uOffset, 1 - v );
  27366. verticesRow.push( index ++ );
  27367. }
  27368. grid.push( verticesRow );
  27369. }
  27370. // indices
  27371. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27372. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27373. const a = grid[ iy ][ ix + 1 ];
  27374. const b = grid[ iy ][ ix ];
  27375. const c = grid[ iy + 1 ][ ix ];
  27376. const d = grid[ iy + 1 ][ ix + 1 ];
  27377. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27378. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27379. }
  27380. }
  27381. // build geometry
  27382. this.setIndex( indices );
  27383. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27384. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27385. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27386. }
  27387. copy( source ) {
  27388. super.copy( source );
  27389. this.parameters = Object.assign( {}, source.parameters );
  27390. return this;
  27391. }
  27392. /**
  27393. * Factory method for creating an instance of this class from the given
  27394. * JSON object.
  27395. *
  27396. * @param {Object} data - A JSON object representing the serialized geometry.
  27397. * @return {SphereGeometry} A new instance.
  27398. */
  27399. static fromJSON( data ) {
  27400. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27401. }
  27402. }
  27403. /**
  27404. * A geometry class for representing an tetrahedron.
  27405. *
  27406. * ```js
  27407. * const geometry = new THREE.TetrahedronGeometry();
  27408. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27409. * const tetrahedron = new THREE.Mesh( geometry, material );
  27410. * scene.add( tetrahedron );
  27411. * ```
  27412. *
  27413. * @augments PolyhedronGeometry
  27414. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27415. */
  27416. class TetrahedronGeometry extends PolyhedronGeometry {
  27417. /**
  27418. * Constructs a new tetrahedron geometry.
  27419. *
  27420. * @param {number} [radius=1] - Radius of the tetrahedron.
  27421. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27422. */
  27423. constructor( radius = 1, detail = 0 ) {
  27424. const vertices = [
  27425. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27426. ];
  27427. const indices = [
  27428. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27429. ];
  27430. super( vertices, indices, radius, detail );
  27431. this.type = 'TetrahedronGeometry';
  27432. /**
  27433. * Holds the constructor parameters that have been
  27434. * used to generate the geometry. Any modification
  27435. * after instantiation does not change the geometry.
  27436. *
  27437. * @type {Object}
  27438. */
  27439. this.parameters = {
  27440. radius: radius,
  27441. detail: detail
  27442. };
  27443. }
  27444. /**
  27445. * Factory method for creating an instance of this class from the given
  27446. * JSON object.
  27447. *
  27448. * @param {Object} data - A JSON object representing the serialized geometry.
  27449. * @return {TetrahedronGeometry} A new instance.
  27450. */
  27451. static fromJSON( data ) {
  27452. return new TetrahedronGeometry( data.radius, data.detail );
  27453. }
  27454. }
  27455. /**
  27456. * A geometry class for representing an torus.
  27457. *
  27458. * ```js
  27459. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27460. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27461. * const torus = new THREE.Mesh( geometry, material );
  27462. * scene.add( torus );
  27463. * ```
  27464. *
  27465. * @augments BufferGeometry
  27466. * @demo scenes/geometry-browser.html#TorusGeometry
  27467. */
  27468. class TorusGeometry extends BufferGeometry {
  27469. /**
  27470. * Constructs a new torus geometry.
  27471. *
  27472. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27473. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27474. * @param {number} [radialSegments=12] - The number of radial segments.
  27475. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27476. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27477. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  27478. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  27479. */
  27480. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27481. super();
  27482. this.type = 'TorusGeometry';
  27483. /**
  27484. * Holds the constructor parameters that have been
  27485. * used to generate the geometry. Any modification
  27486. * after instantiation does not change the geometry.
  27487. *
  27488. * @type {Object}
  27489. */
  27490. this.parameters = {
  27491. radius: radius,
  27492. tube: tube,
  27493. radialSegments: radialSegments,
  27494. tubularSegments: tubularSegments,
  27495. arc: arc,
  27496. thetaStart: thetaStart,
  27497. thetaLength: thetaLength,
  27498. };
  27499. radialSegments = Math.floor( radialSegments );
  27500. tubularSegments = Math.floor( tubularSegments );
  27501. // buffers
  27502. const indices = [];
  27503. const vertices = [];
  27504. const normals = [];
  27505. const uvs = [];
  27506. // helper variables
  27507. const center = new Vector3();
  27508. const vertex = new Vector3();
  27509. const normal = new Vector3();
  27510. // generate vertices, normals and uvs
  27511. for ( let j = 0; j <= radialSegments; j ++ ) {
  27512. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  27513. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27514. const u = i / tubularSegments * arc;
  27515. // vertex
  27516. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27517. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27518. vertex.z = tube * Math.sin( v );
  27519. vertices.push( vertex.x, vertex.y, vertex.z );
  27520. // normal
  27521. center.x = radius * Math.cos( u );
  27522. center.y = radius * Math.sin( u );
  27523. normal.subVectors( vertex, center ).normalize();
  27524. normals.push( normal.x, normal.y, normal.z );
  27525. // uv
  27526. uvs.push( i / tubularSegments );
  27527. uvs.push( j / radialSegments );
  27528. }
  27529. }
  27530. // generate indices
  27531. for ( let j = 1; j <= radialSegments; j ++ ) {
  27532. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27533. // indices
  27534. const a = ( tubularSegments + 1 ) * j + i - 1;
  27535. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27536. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27537. const d = ( tubularSegments + 1 ) * j + i;
  27538. // faces
  27539. indices.push( a, b, d );
  27540. indices.push( b, c, d );
  27541. }
  27542. }
  27543. // build geometry
  27544. this.setIndex( indices );
  27545. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27546. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27547. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27548. }
  27549. copy( source ) {
  27550. super.copy( source );
  27551. this.parameters = Object.assign( {}, source.parameters );
  27552. return this;
  27553. }
  27554. /**
  27555. * Factory method for creating an instance of this class from the given
  27556. * JSON object.
  27557. *
  27558. * @param {Object} data - A JSON object representing the serialized geometry.
  27559. * @return {TorusGeometry} A new instance.
  27560. */
  27561. static fromJSON( data ) {
  27562. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27563. }
  27564. }
  27565. /**
  27566. * Creates a torus knot, the particular shape of which is defined by a pair
  27567. * of coprime integers, p and q. If p and q are not coprime, the result will
  27568. * be a torus link.
  27569. *
  27570. * ```js
  27571. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27572. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27573. * const torusKnot = new THREE.Mesh( geometry, material );
  27574. * scene.add( torusKnot );
  27575. * ```
  27576. *
  27577. * @augments BufferGeometry
  27578. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27579. */
  27580. class TorusKnotGeometry extends BufferGeometry {
  27581. /**
  27582. * Constructs a new torus knot geometry.
  27583. *
  27584. * @param {number} [radius=1] - Radius of the torus knot.
  27585. * @param {number} [tube=0.4] - Radius of the tube.
  27586. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27587. * @param {number} [radialSegments=8] - The number of radial segments.
  27588. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27589. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27590. */
  27591. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27592. super();
  27593. this.type = 'TorusKnotGeometry';
  27594. /**
  27595. * Holds the constructor parameters that have been
  27596. * used to generate the geometry. Any modification
  27597. * after instantiation does not change the geometry.
  27598. *
  27599. * @type {Object}
  27600. */
  27601. this.parameters = {
  27602. radius: radius,
  27603. tube: tube,
  27604. tubularSegments: tubularSegments,
  27605. radialSegments: radialSegments,
  27606. p: p,
  27607. q: q
  27608. };
  27609. tubularSegments = Math.floor( tubularSegments );
  27610. radialSegments = Math.floor( radialSegments );
  27611. // buffers
  27612. const indices = [];
  27613. const vertices = [];
  27614. const normals = [];
  27615. const uvs = [];
  27616. // helper variables
  27617. const vertex = new Vector3();
  27618. const normal = new Vector3();
  27619. const P1 = new Vector3();
  27620. const P2 = new Vector3();
  27621. const B = new Vector3();
  27622. const T = new Vector3();
  27623. const N = new Vector3();
  27624. // generate vertices, normals and uvs
  27625. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27626. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27627. const u = i / tubularSegments * p * Math.PI * 2;
  27628. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27629. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27630. calculatePositionOnCurve( u, p, q, radius, P1 );
  27631. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27632. // calculate orthonormal basis
  27633. T.subVectors( P2, P1 );
  27634. N.addVectors( P2, P1 );
  27635. B.crossVectors( T, N );
  27636. N.crossVectors( B, T );
  27637. // normalize B, N. T can be ignored, we don't use it
  27638. B.normalize();
  27639. N.normalize();
  27640. for ( let j = 0; j <= radialSegments; ++ j ) {
  27641. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27642. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27643. const v = j / radialSegments * Math.PI * 2;
  27644. const cx = - tube * Math.cos( v );
  27645. const cy = tube * Math.sin( v );
  27646. // now calculate the final vertex position.
  27647. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27648. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27649. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27650. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27651. vertices.push( vertex.x, vertex.y, vertex.z );
  27652. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27653. normal.subVectors( vertex, P1 ).normalize();
  27654. normals.push( normal.x, normal.y, normal.z );
  27655. // uv
  27656. uvs.push( i / tubularSegments );
  27657. uvs.push( j / radialSegments );
  27658. }
  27659. }
  27660. // generate indices
  27661. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27662. for ( let i = 1; i <= radialSegments; i ++ ) {
  27663. // indices
  27664. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27665. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27666. const c = ( radialSegments + 1 ) * j + i;
  27667. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27668. // faces
  27669. indices.push( a, b, d );
  27670. indices.push( b, c, d );
  27671. }
  27672. }
  27673. // build geometry
  27674. this.setIndex( indices );
  27675. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27676. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27677. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27678. // this function calculates the current position on the torus curve
  27679. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27680. const cu = Math.cos( u );
  27681. const su = Math.sin( u );
  27682. const quOverP = q / p * u;
  27683. const cs = Math.cos( quOverP );
  27684. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27685. position.y = radius * ( 2 + cs ) * su * 0.5;
  27686. position.z = radius * Math.sin( quOverP ) * 0.5;
  27687. }
  27688. }
  27689. copy( source ) {
  27690. super.copy( source );
  27691. this.parameters = Object.assign( {}, source.parameters );
  27692. return this;
  27693. }
  27694. /**
  27695. * Factory method for creating an instance of this class from the given
  27696. * JSON object.
  27697. *
  27698. * @param {Object} data - A JSON object representing the serialized geometry.
  27699. * @return {TorusKnotGeometry} A new instance.
  27700. */
  27701. static fromJSON( data ) {
  27702. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27703. }
  27704. }
  27705. /**
  27706. * Creates a tube that extrudes along a 3D curve.
  27707. *
  27708. * ```js
  27709. * class CustomSinCurve extends THREE.Curve {
  27710. *
  27711. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27712. *
  27713. * const tx = t * 3 - 1.5;
  27714. * const ty = Math.sin( 2 * Math.PI * t );
  27715. * const tz = 0;
  27716. *
  27717. * return optionalTarget.set( tx, ty, tz );
  27718. * }
  27719. *
  27720. * }
  27721. *
  27722. * const path = new CustomSinCurve( 10 );
  27723. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27724. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27725. * const mesh = new THREE.Mesh( geometry, material );
  27726. * scene.add( mesh );
  27727. * ```
  27728. *
  27729. * @augments BufferGeometry
  27730. * @demo scenes/geometry-browser.html#TubeGeometry
  27731. */
  27732. class TubeGeometry extends BufferGeometry {
  27733. /**
  27734. * Constructs a new tube geometry.
  27735. *
  27736. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27737. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27738. * @param {number} [radius=1] -The radius of the tube.
  27739. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27740. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27741. */
  27742. 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 ) {
  27743. super();
  27744. this.type = 'TubeGeometry';
  27745. /**
  27746. * Holds the constructor parameters that have been
  27747. * used to generate the geometry. Any modification
  27748. * after instantiation does not change the geometry.
  27749. *
  27750. * @type {Object}
  27751. */
  27752. this.parameters = {
  27753. path: path,
  27754. tubularSegments: tubularSegments,
  27755. radius: radius,
  27756. radialSegments: radialSegments,
  27757. closed: closed
  27758. };
  27759. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27760. // expose internals
  27761. this.tangents = frames.tangents;
  27762. this.normals = frames.normals;
  27763. this.binormals = frames.binormals;
  27764. // helper variables
  27765. const vertex = new Vector3();
  27766. const normal = new Vector3();
  27767. const uv = new Vector2();
  27768. let P = new Vector3();
  27769. // buffer
  27770. const vertices = [];
  27771. const normals = [];
  27772. const uvs = [];
  27773. const indices = [];
  27774. // create buffer data
  27775. generateBufferData();
  27776. // build geometry
  27777. this.setIndex( indices );
  27778. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27779. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27780. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27781. // functions
  27782. function generateBufferData() {
  27783. for ( let i = 0; i < tubularSegments; i ++ ) {
  27784. generateSegment( i );
  27785. }
  27786. // if the geometry is not closed, generate the last row of vertices and normals
  27787. // at the regular position on the given path
  27788. //
  27789. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27790. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27791. // uvs are generated in a separate function.
  27792. // this makes it easy compute correct values for closed geometries
  27793. generateUVs();
  27794. // finally create faces
  27795. generateIndices();
  27796. }
  27797. function generateSegment( i ) {
  27798. // we use getPointAt to sample evenly distributed points from the given path
  27799. P = path.getPointAt( i / tubularSegments, P );
  27800. // retrieve corresponding normal and binormal
  27801. const N = frames.normals[ i ];
  27802. const B = frames.binormals[ i ];
  27803. // generate normals and vertices for the current segment
  27804. for ( let j = 0; j <= radialSegments; j ++ ) {
  27805. const v = j / radialSegments * Math.PI * 2;
  27806. const sin = Math.sin( v );
  27807. const cos = - Math.cos( v );
  27808. // normal
  27809. normal.x = ( cos * N.x + sin * B.x );
  27810. normal.y = ( cos * N.y + sin * B.y );
  27811. normal.z = ( cos * N.z + sin * B.z );
  27812. normal.normalize();
  27813. normals.push( normal.x, normal.y, normal.z );
  27814. // vertex
  27815. vertex.x = P.x + radius * normal.x;
  27816. vertex.y = P.y + radius * normal.y;
  27817. vertex.z = P.z + radius * normal.z;
  27818. vertices.push( vertex.x, vertex.y, vertex.z );
  27819. }
  27820. }
  27821. function generateIndices() {
  27822. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27823. for ( let i = 1; i <= radialSegments; i ++ ) {
  27824. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27825. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27826. const c = ( radialSegments + 1 ) * j + i;
  27827. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27828. // faces
  27829. indices.push( a, b, d );
  27830. indices.push( b, c, d );
  27831. }
  27832. }
  27833. }
  27834. function generateUVs() {
  27835. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27836. for ( let j = 0; j <= radialSegments; j ++ ) {
  27837. uv.x = i / tubularSegments;
  27838. uv.y = j / radialSegments;
  27839. uvs.push( uv.x, uv.y );
  27840. }
  27841. }
  27842. }
  27843. }
  27844. copy( source ) {
  27845. super.copy( source );
  27846. this.parameters = Object.assign( {}, source.parameters );
  27847. return this;
  27848. }
  27849. toJSON() {
  27850. const data = super.toJSON();
  27851. data.path = this.parameters.path.toJSON();
  27852. return data;
  27853. }
  27854. /**
  27855. * Factory method for creating an instance of this class from the given
  27856. * JSON object.
  27857. *
  27858. * @param {Object} data - A JSON object representing the serialized geometry.
  27859. * @return {TubeGeometry} A new instance.
  27860. */
  27861. static fromJSON( data ) {
  27862. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27863. // User defined curves or instances of CurvePath will not be deserialized.
  27864. return new TubeGeometry(
  27865. new Curves[ data.path.type ]().fromJSON( data.path ),
  27866. data.tubularSegments,
  27867. data.radius,
  27868. data.radialSegments,
  27869. data.closed
  27870. );
  27871. }
  27872. }
  27873. /**
  27874. * Can be used as a helper object to visualize a geometry as a wireframe.
  27875. *
  27876. * ```js
  27877. * const geometry = new THREE.SphereGeometry();
  27878. *
  27879. * const wireframe = new THREE.WireframeGeometry( geometry );
  27880. *
  27881. * const line = new THREE.LineSegments( wireframe );
  27882. * line.material.depthWrite = false;
  27883. * line.material.opacity = 0.25;
  27884. * line.material.transparent = true;
  27885. *
  27886. * scene.add( line );
  27887. * ```
  27888. *
  27889. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27890. *
  27891. * @augments BufferGeometry
  27892. */
  27893. class WireframeGeometry extends BufferGeometry {
  27894. /**
  27895. * Constructs a new wireframe geometry.
  27896. *
  27897. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27898. */
  27899. constructor( geometry = null ) {
  27900. super();
  27901. this.type = 'WireframeGeometry';
  27902. /**
  27903. * Holds the constructor parameters that have been
  27904. * used to generate the geometry. Any modification
  27905. * after instantiation does not change the geometry.
  27906. *
  27907. * @type {Object}
  27908. */
  27909. this.parameters = {
  27910. geometry: geometry
  27911. };
  27912. if ( geometry !== null ) {
  27913. // buffer
  27914. const vertices = [];
  27915. const edges = new Set();
  27916. // helper variables
  27917. const start = new Vector3();
  27918. const end = new Vector3();
  27919. if ( geometry.index !== null ) {
  27920. // indexed BufferGeometry
  27921. const position = geometry.attributes.position;
  27922. const indices = geometry.index;
  27923. let groups = geometry.groups;
  27924. if ( groups.length === 0 ) {
  27925. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27926. }
  27927. // create a data structure that contains all edges without duplicates
  27928. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27929. const group = groups[ o ];
  27930. const groupStart = group.start;
  27931. const groupCount = group.count;
  27932. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27933. for ( let j = 0; j < 3; j ++ ) {
  27934. const index1 = indices.getX( i + j );
  27935. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27936. start.fromBufferAttribute( position, index1 );
  27937. end.fromBufferAttribute( position, index2 );
  27938. if ( isUniqueEdge( start, end, edges ) === true ) {
  27939. vertices.push( start.x, start.y, start.z );
  27940. vertices.push( end.x, end.y, end.z );
  27941. }
  27942. }
  27943. }
  27944. }
  27945. } else {
  27946. // non-indexed BufferGeometry
  27947. const position = geometry.attributes.position;
  27948. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27949. for ( let j = 0; j < 3; j ++ ) {
  27950. // three edges per triangle, an edge is represented as (index1, index2)
  27951. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27952. const index1 = 3 * i + j;
  27953. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27954. start.fromBufferAttribute( position, index1 );
  27955. end.fromBufferAttribute( position, index2 );
  27956. if ( isUniqueEdge( start, end, edges ) === true ) {
  27957. vertices.push( start.x, start.y, start.z );
  27958. vertices.push( end.x, end.y, end.z );
  27959. }
  27960. }
  27961. }
  27962. }
  27963. // build geometry
  27964. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27965. }
  27966. }
  27967. copy( source ) {
  27968. super.copy( source );
  27969. this.parameters = Object.assign( {}, source.parameters );
  27970. return this;
  27971. }
  27972. }
  27973. function isUniqueEdge( start, end, edges ) {
  27974. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27975. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27976. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27977. return false;
  27978. } else {
  27979. edges.add( hash1 );
  27980. edges.add( hash2 );
  27981. return true;
  27982. }
  27983. }
  27984. var Geometries = /*#__PURE__*/Object.freeze({
  27985. __proto__: null,
  27986. BoxGeometry: BoxGeometry,
  27987. CapsuleGeometry: CapsuleGeometry,
  27988. CircleGeometry: CircleGeometry,
  27989. ConeGeometry: ConeGeometry,
  27990. CylinderGeometry: CylinderGeometry,
  27991. DodecahedronGeometry: DodecahedronGeometry,
  27992. EdgesGeometry: EdgesGeometry,
  27993. ExtrudeGeometry: ExtrudeGeometry,
  27994. IcosahedronGeometry: IcosahedronGeometry,
  27995. LatheGeometry: LatheGeometry,
  27996. OctahedronGeometry: OctahedronGeometry,
  27997. PlaneGeometry: PlaneGeometry,
  27998. PolyhedronGeometry: PolyhedronGeometry,
  27999. RingGeometry: RingGeometry,
  28000. ShapeGeometry: ShapeGeometry,
  28001. SphereGeometry: SphereGeometry,
  28002. TetrahedronGeometry: TetrahedronGeometry,
  28003. TorusGeometry: TorusGeometry,
  28004. TorusKnotGeometry: TorusKnotGeometry,
  28005. TubeGeometry: TubeGeometry,
  28006. WireframeGeometry: WireframeGeometry
  28007. });
  28008. /**
  28009. * This material can receive shadows, but otherwise is completely transparent.
  28010. *
  28011. * ```js
  28012. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  28013. * geometry.rotateX( - Math.PI / 2 );
  28014. *
  28015. * const material = new THREE.ShadowMaterial();
  28016. * material.opacity = 0.2;
  28017. *
  28018. * const plane = new THREE.Mesh( geometry, material );
  28019. * plane.position.y = -200;
  28020. * plane.receiveShadow = true;
  28021. * scene.add( plane );
  28022. * ```
  28023. *
  28024. * @augments Material
  28025. */
  28026. class ShadowMaterial extends Material {
  28027. /**
  28028. * Constructs a new shadow material.
  28029. *
  28030. * @param {Object} [parameters] - An object with one or more properties
  28031. * defining the material's appearance. Any property of the material
  28032. * (including any property from inherited materials) can be passed
  28033. * in here. Color values can be passed any type of value accepted
  28034. * by {@link Color#set}.
  28035. */
  28036. constructor( parameters ) {
  28037. super();
  28038. /**
  28039. * This flag can be used for type testing.
  28040. *
  28041. * @type {boolean}
  28042. * @readonly
  28043. * @default true
  28044. */
  28045. this.isShadowMaterial = true;
  28046. this.type = 'ShadowMaterial';
  28047. /**
  28048. * Color of the material.
  28049. *
  28050. * @type {Color}
  28051. * @default (0,0,0)
  28052. */
  28053. this.color = new Color( 0x000000 );
  28054. /**
  28055. * Overwritten since shadow materials are transparent
  28056. * by default.
  28057. *
  28058. * @type {boolean}
  28059. * @default true
  28060. */
  28061. this.transparent = true;
  28062. /**
  28063. * Whether the material is affected by fog or not.
  28064. *
  28065. * @type {boolean}
  28066. * @default true
  28067. */
  28068. this.fog = true;
  28069. this.setValues( parameters );
  28070. }
  28071. copy( source ) {
  28072. super.copy( source );
  28073. this.color.copy( source.color );
  28074. this.fog = source.fog;
  28075. return this;
  28076. }
  28077. }
  28078. /**
  28079. * This class works just like {@link ShaderMaterial}, except that definitions
  28080. * of built-in uniforms and attributes are not automatically prepended to the
  28081. * GLSL shader code.
  28082. *
  28083. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  28084. *
  28085. * @augments ShaderMaterial
  28086. */
  28087. class RawShaderMaterial extends ShaderMaterial {
  28088. /**
  28089. * Constructs a new raw shader material.
  28090. *
  28091. * @param {Object} [parameters] - An object with one or more properties
  28092. * defining the material's appearance. Any property of the material
  28093. * (including any property from inherited materials) can be passed
  28094. * in here. Color values can be passed any type of value accepted
  28095. * by {@link Color#set}.
  28096. */
  28097. constructor( parameters ) {
  28098. super( parameters );
  28099. /**
  28100. * This flag can be used for type testing.
  28101. *
  28102. * @type {boolean}
  28103. * @readonly
  28104. * @default true
  28105. */
  28106. this.isRawShaderMaterial = true;
  28107. this.type = 'RawShaderMaterial';
  28108. }
  28109. }
  28110. /**
  28111. * A standard physically based material, using Metallic-Roughness workflow.
  28112. *
  28113. * Physically based rendering (PBR) has recently become the standard in many
  28114. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  28115. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  28116. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  28117. *
  28118. * This approach differs from older approaches in that instead of using
  28119. * approximations for the way in which light interacts with a surface, a
  28120. * physically correct model is used. The idea is that, instead of tweaking
  28121. * materials to look good under specific lighting, a material can be created
  28122. * that will react 'correctly' under all lighting scenarios.
  28123. *
  28124. * In practice this gives a more accurate and realistic looking result than
  28125. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  28126. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  28127. * shading.
  28128. *
  28129. * Note that for best results you should always specify an environment map when using this material.
  28130. *
  28131. * For a non-technical introduction to the concept of PBR and how to set up a
  28132. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  28133. *
  28134. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  28135. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  28136. *
  28137. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  28138. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  28139. * (pdf), by Brent Burley.
  28140. *
  28141. * @augments Material
  28142. * @demo scenes/material-browser.html#MeshStandardMaterial
  28143. */
  28144. class MeshStandardMaterial extends Material {
  28145. /**
  28146. * Constructs a new mesh standard material.
  28147. *
  28148. * @param {Object} [parameters] - An object with one or more properties
  28149. * defining the material's appearance. Any property of the material
  28150. * (including any property from inherited materials) can be passed
  28151. * in here. Color values can be passed any type of value accepted
  28152. * by {@link Color#set}.
  28153. */
  28154. constructor( parameters ) {
  28155. super();
  28156. /**
  28157. * This flag can be used for type testing.
  28158. *
  28159. * @type {boolean}
  28160. * @readonly
  28161. * @default true
  28162. */
  28163. this.isMeshStandardMaterial = true;
  28164. this.type = 'MeshStandardMaterial';
  28165. this.defines = { 'STANDARD': '' };
  28166. /**
  28167. * Color of the material.
  28168. *
  28169. * @type {Color}
  28170. * @default (1,1,1)
  28171. */
  28172. this.color = new Color( 0xffffff ); // diffuse
  28173. /**
  28174. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  28175. * means fully diffuse. If `roughnessMap` is also provided,
  28176. * both values are multiplied.
  28177. *
  28178. * @type {number}
  28179. * @default 1
  28180. */
  28181. this.roughness = 1.0;
  28182. /**
  28183. * How much the material is like a metal. Non-metallic materials such as wood
  28184. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  28185. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  28186. * If `metalnessMap` is also provided, both values are multiplied.
  28187. *
  28188. * @type {number}
  28189. * @default 0
  28190. */
  28191. this.metalness = 0.0;
  28192. /**
  28193. * The color map. May optionally include an alpha channel, typically combined
  28194. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28195. * color is modulated by the diffuse `color`.
  28196. *
  28197. * @type {?Texture}
  28198. * @default null
  28199. */
  28200. this.map = null;
  28201. /**
  28202. * The light map. Requires a second set of UVs.
  28203. *
  28204. * @type {?Texture}
  28205. * @default null
  28206. */
  28207. this.lightMap = null;
  28208. /**
  28209. * Intensity of the baked light.
  28210. *
  28211. * @type {number}
  28212. * @default 1
  28213. */
  28214. this.lightMapIntensity = 1.0;
  28215. /**
  28216. * The red channel of this texture is used as the ambient occlusion map.
  28217. * Requires a second set of UVs.
  28218. *
  28219. * @type {?Texture}
  28220. * @default null
  28221. */
  28222. this.aoMap = null;
  28223. /**
  28224. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28225. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28226. * red channel is also `1`, ambient light is fully occluded on a surface.
  28227. *
  28228. * @type {number}
  28229. * @default 1
  28230. */
  28231. this.aoMapIntensity = 1.0;
  28232. /**
  28233. * Emissive (light) color of the material, essentially a solid color
  28234. * unaffected by other lighting.
  28235. *
  28236. * @type {Color}
  28237. * @default (0,0,0)
  28238. */
  28239. this.emissive = new Color( 0x000000 );
  28240. /**
  28241. * Intensity of the emissive light. Modulates the emissive color.
  28242. *
  28243. * @type {number}
  28244. * @default 1
  28245. */
  28246. this.emissiveIntensity = 1.0;
  28247. /**
  28248. * Set emissive (glow) map. The emissive map color is modulated by the
  28249. * emissive color and the emissive intensity. If you have an emissive map,
  28250. * be sure to set the emissive color to something other than black.
  28251. *
  28252. * @type {?Texture}
  28253. * @default null
  28254. */
  28255. this.emissiveMap = null;
  28256. /**
  28257. * The texture to create a bump map. The black and white values map to the
  28258. * perceived depth in relation to the lights. Bump doesn't actually affect
  28259. * the geometry of the object, only the lighting. If a normal map is defined
  28260. * this will be ignored.
  28261. *
  28262. * @type {?Texture}
  28263. * @default null
  28264. */
  28265. this.bumpMap = null;
  28266. /**
  28267. * How much the bump map affects the material. Typical range is `[0,1]`.
  28268. *
  28269. * @type {number}
  28270. * @default 1
  28271. */
  28272. this.bumpScale = 1;
  28273. /**
  28274. * The texture to create a normal map. The RGB values affect the surface
  28275. * normal for each pixel fragment and change the way the color is lit. Normal
  28276. * maps do not change the actual shape of the surface, only the lighting. In
  28277. * case the material has a normal map authored using the left handed
  28278. * convention, the `y` component of `normalScale` should be negated to compensate
  28279. * for the different handedness.
  28280. *
  28281. * @type {?Texture}
  28282. * @default null
  28283. */
  28284. this.normalMap = null;
  28285. /**
  28286. * The type of normal map.
  28287. *
  28288. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28289. * @default TangentSpaceNormalMap
  28290. */
  28291. this.normalMapType = TangentSpaceNormalMap;
  28292. /**
  28293. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28294. *
  28295. * @type {Vector2}
  28296. * @default (1,1)
  28297. */
  28298. this.normalScale = new Vector2( 1, 1 );
  28299. /**
  28300. * The displacement map affects the position of the mesh's vertices. Unlike
  28301. * other maps which only affect the light and shade of the material the
  28302. * displaced vertices can cast shadows, block other objects, and otherwise
  28303. * act as real geometry. The displacement texture is an image where the value
  28304. * of each pixel (white being the highest) is mapped against, and
  28305. * repositions, the vertices of the mesh.
  28306. *
  28307. * @type {?Texture}
  28308. * @default null
  28309. */
  28310. this.displacementMap = null;
  28311. /**
  28312. * How much the displacement map affects the mesh (where black is no
  28313. * displacement, and white is maximum displacement). Without a displacement
  28314. * map set, this value is not applied.
  28315. *
  28316. * @type {number}
  28317. * @default 0
  28318. */
  28319. this.displacementScale = 1;
  28320. /**
  28321. * The offset of the displacement map's values on the mesh's vertices.
  28322. * The bias is added to the scaled sample of the displacement map.
  28323. * Without a displacement map set, this value is not applied.
  28324. *
  28325. * @type {number}
  28326. * @default 0
  28327. */
  28328. this.displacementBias = 0;
  28329. /**
  28330. * The green channel of this texture is used to alter the roughness of the
  28331. * material.
  28332. *
  28333. * @type {?Texture}
  28334. * @default null
  28335. */
  28336. this.roughnessMap = null;
  28337. /**
  28338. * The blue channel of this texture is used to alter the metalness of the
  28339. * material.
  28340. *
  28341. * @type {?Texture}
  28342. * @default null
  28343. */
  28344. this.metalnessMap = null;
  28345. /**
  28346. * The alpha map is a grayscale texture that controls the opacity across the
  28347. * surface (black: fully transparent; white: fully opaque).
  28348. *
  28349. * Only the color of the texture is used, ignoring the alpha channel if one
  28350. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28351. * when sampling this texture due to the extra bit of precision provided for
  28352. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28353. * luminance/alpha textures will also still work as expected.
  28354. *
  28355. * @type {?Texture}
  28356. * @default null
  28357. */
  28358. this.alphaMap = null;
  28359. /**
  28360. * The environment map. To ensure a physically correct rendering, environment maps
  28361. * are internally pre-processed with {@link PMREMGenerator}.
  28362. *
  28363. * @type {?Texture}
  28364. * @default null
  28365. */
  28366. this.envMap = null;
  28367. /**
  28368. * The rotation of the environment map in radians.
  28369. *
  28370. * @type {Euler}
  28371. * @default (0,0,0)
  28372. */
  28373. this.envMapRotation = new Euler();
  28374. /**
  28375. * Scales the effect of the environment map by multiplying its color.
  28376. *
  28377. * @type {number}
  28378. * @default 1
  28379. */
  28380. this.envMapIntensity = 1.0;
  28381. /**
  28382. * Renders the geometry as a wireframe.
  28383. *
  28384. * @type {boolean}
  28385. * @default false
  28386. */
  28387. this.wireframe = false;
  28388. /**
  28389. * Controls the thickness of the wireframe.
  28390. *
  28391. * Can only be used with {@link SVGRenderer}.
  28392. *
  28393. * @type {number}
  28394. * @default 1
  28395. */
  28396. this.wireframeLinewidth = 1;
  28397. /**
  28398. * Defines appearance of wireframe ends.
  28399. *
  28400. * Can only be used with {@link SVGRenderer}.
  28401. *
  28402. * @type {('round'|'bevel'|'miter')}
  28403. * @default 'round'
  28404. */
  28405. this.wireframeLinecap = 'round';
  28406. /**
  28407. * Defines appearance of wireframe joints.
  28408. *
  28409. * Can only be used with {@link SVGRenderer}.
  28410. *
  28411. * @type {('round'|'bevel'|'miter')}
  28412. * @default 'round'
  28413. */
  28414. this.wireframeLinejoin = 'round';
  28415. /**
  28416. * Whether the material is rendered with flat shading or not.
  28417. *
  28418. * @type {boolean}
  28419. * @default false
  28420. */
  28421. this.flatShading = false;
  28422. /**
  28423. * Whether the material is affected by fog or not.
  28424. *
  28425. * @type {boolean}
  28426. * @default true
  28427. */
  28428. this.fog = true;
  28429. this.setValues( parameters );
  28430. }
  28431. copy( source ) {
  28432. super.copy( source );
  28433. this.defines = { 'STANDARD': '' };
  28434. this.color.copy( source.color );
  28435. this.roughness = source.roughness;
  28436. this.metalness = source.metalness;
  28437. this.map = source.map;
  28438. this.lightMap = source.lightMap;
  28439. this.lightMapIntensity = source.lightMapIntensity;
  28440. this.aoMap = source.aoMap;
  28441. this.aoMapIntensity = source.aoMapIntensity;
  28442. this.emissive.copy( source.emissive );
  28443. this.emissiveMap = source.emissiveMap;
  28444. this.emissiveIntensity = source.emissiveIntensity;
  28445. this.bumpMap = source.bumpMap;
  28446. this.bumpScale = source.bumpScale;
  28447. this.normalMap = source.normalMap;
  28448. this.normalMapType = source.normalMapType;
  28449. this.normalScale.copy( source.normalScale );
  28450. this.displacementMap = source.displacementMap;
  28451. this.displacementScale = source.displacementScale;
  28452. this.displacementBias = source.displacementBias;
  28453. this.roughnessMap = source.roughnessMap;
  28454. this.metalnessMap = source.metalnessMap;
  28455. this.alphaMap = source.alphaMap;
  28456. this.envMap = source.envMap;
  28457. this.envMapRotation.copy( source.envMapRotation );
  28458. this.envMapIntensity = source.envMapIntensity;
  28459. this.wireframe = source.wireframe;
  28460. this.wireframeLinewidth = source.wireframeLinewidth;
  28461. this.wireframeLinecap = source.wireframeLinecap;
  28462. this.wireframeLinejoin = source.wireframeLinejoin;
  28463. this.flatShading = source.flatShading;
  28464. this.fog = source.fog;
  28465. return this;
  28466. }
  28467. }
  28468. /**
  28469. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28470. * physically-based rendering properties:
  28471. *
  28472. * - Anisotropy: Ability to represent the anisotropic property of materials
  28473. * as observable with brushed metals.
  28474. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28475. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28476. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28477. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28478. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28479. * wings of many insects.
  28480. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28481. * transparent materials are less reflective. Physically-based transmission provides a more
  28482. * realistic option for thin, transparent surfaces like glass.
  28483. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28484. * - Sheen: Can be used for representing cloth and fabric materials.
  28485. *
  28486. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28487. * higher performance cost, per pixel, than other three.js materials. Most
  28488. * effects are disabled by default, and add cost as they are enabled. For
  28489. * best results, always specify an environment map when using this material.
  28490. *
  28491. * @augments MeshStandardMaterial
  28492. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28493. */
  28494. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28495. /**
  28496. * Constructs a new mesh physical material.
  28497. *
  28498. * @param {Object} [parameters] - An object with one or more properties
  28499. * defining the material's appearance. Any property of the material
  28500. * (including any property from inherited materials) can be passed
  28501. * in here. Color values can be passed any type of value accepted
  28502. * by {@link Color#set}.
  28503. */
  28504. constructor( parameters ) {
  28505. super();
  28506. /**
  28507. * This flag can be used for type testing.
  28508. *
  28509. * @type {boolean}
  28510. * @readonly
  28511. * @default true
  28512. */
  28513. this.isMeshPhysicalMaterial = true;
  28514. this.defines = {
  28515. 'STANDARD': '',
  28516. 'PHYSICAL': ''
  28517. };
  28518. this.type = 'MeshPhysicalMaterial';
  28519. /**
  28520. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28521. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28522. * property provides additional rotation to the vectors in the texture.
  28523. *
  28524. * @type {number}
  28525. * @default 1
  28526. */
  28527. this.anisotropyRotation = 0;
  28528. /**
  28529. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28530. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28531. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28532. *
  28533. * @type {?Texture}
  28534. * @default null
  28535. */
  28536. this.anisotropyMap = null;
  28537. /**
  28538. * The red channel of this texture is multiplied against `clearcoat`,
  28539. * for per-pixel control over a coating's intensity.
  28540. *
  28541. * @type {?Texture}
  28542. * @default null
  28543. */
  28544. this.clearcoatMap = null;
  28545. /**
  28546. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28547. *
  28548. * @type {number}
  28549. * @default 0
  28550. */
  28551. this.clearcoatRoughness = 0.0;
  28552. /**
  28553. * The green channel of this texture is multiplied against
  28554. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28555. *
  28556. * @type {?Texture}
  28557. * @default null
  28558. */
  28559. this.clearcoatRoughnessMap = null;
  28560. /**
  28561. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28562. * `(0,0)` to `(1,1)`.
  28563. *
  28564. * @type {Vector2}
  28565. * @default (1,1)
  28566. */
  28567. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28568. /**
  28569. * Can be used to enable independent normals for the clear coat layer.
  28570. *
  28571. * @type {?Texture}
  28572. * @default null
  28573. */
  28574. this.clearcoatNormalMap = null;
  28575. /**
  28576. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28577. *
  28578. * @type {number}
  28579. * @default 1.5
  28580. */
  28581. this.ior = 1.5;
  28582. /**
  28583. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28584. * corresponds to an index-of-refraction of `1.5`.
  28585. *
  28586. * This models the reflectivity of non-metallic materials. It has no effect
  28587. * when `metalness` is `1.0`
  28588. *
  28589. * @name MeshPhysicalMaterial#reflectivity
  28590. * @type {number}
  28591. * @default 0.5
  28592. */
  28593. Object.defineProperty( this, 'reflectivity', {
  28594. get: function () {
  28595. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28596. },
  28597. set: function ( reflectivity ) {
  28598. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28599. }
  28600. } );
  28601. /**
  28602. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28603. * control over iridescence.
  28604. *
  28605. * @type {?Texture}
  28606. * @default null
  28607. */
  28608. this.iridescenceMap = null;
  28609. /**
  28610. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28611. * Between `1.0` to `2.333`.
  28612. *
  28613. * @type {number}
  28614. * @default 1.3
  28615. */
  28616. this.iridescenceIOR = 1.3;
  28617. /**
  28618. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28619. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28620. *
  28621. * @type {Array<number,number>}
  28622. * @default [100,400]
  28623. */
  28624. this.iridescenceThicknessRange = [ 100, 400 ];
  28625. /**
  28626. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28627. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28628. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28629. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28630. * - Values in-between will linearly interpolate between the elements of the array.
  28631. *
  28632. * @type {?Texture}
  28633. * @default null
  28634. */
  28635. this.iridescenceThicknessMap = null;
  28636. /**
  28637. * The sheen tint.
  28638. *
  28639. * @type {Color}
  28640. * @default (0,0,0)
  28641. */
  28642. this.sheenColor = new Color( 0x000000 );
  28643. /**
  28644. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28645. * over sheen tint.
  28646. *
  28647. * @type {?Texture}
  28648. * @default null
  28649. */
  28650. this.sheenColorMap = null;
  28651. /**
  28652. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28653. *
  28654. * @type {number}
  28655. * @default 1
  28656. */
  28657. this.sheenRoughness = 1.0;
  28658. /**
  28659. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28660. * over sheen roughness.
  28661. *
  28662. * @type {?Texture}
  28663. * @default null
  28664. */
  28665. this.sheenRoughnessMap = null;
  28666. /**
  28667. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28668. * optical transparency.
  28669. *
  28670. * @type {?Texture}
  28671. * @default null
  28672. */
  28673. this.transmissionMap = null;
  28674. /**
  28675. * The thickness of the volume beneath the surface. The value is given in the
  28676. * coordinate space of the mesh. If the value is `0` the material is
  28677. * thin-walled. Otherwise the material is a volume boundary.
  28678. *
  28679. * @type {number}
  28680. * @default 0
  28681. */
  28682. this.thickness = 0;
  28683. /**
  28684. * A texture that defines the thickness, stored in the green channel. This will
  28685. * be multiplied by `thickness`.
  28686. *
  28687. * @type {?Texture}
  28688. * @default null
  28689. */
  28690. this.thicknessMap = null;
  28691. /**
  28692. * Density of the medium given as the average distance that light travels in
  28693. * the medium before interacting with a particle. The value is given in world
  28694. * space units, and must be greater than zero.
  28695. *
  28696. * @type {number}
  28697. * @default Infinity
  28698. */
  28699. this.attenuationDistance = Infinity;
  28700. /**
  28701. * The color that white light turns into due to absorption when reaching the
  28702. * attenuation distance.
  28703. *
  28704. * @type {Color}
  28705. * @default (1,1,1)
  28706. */
  28707. this.attenuationColor = new Color( 1, 1, 1 );
  28708. /**
  28709. * A float that scales the amount of specular reflection for non-metals only.
  28710. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28711. *
  28712. * @type {number}
  28713. * @default 1
  28714. */
  28715. this.specularIntensity = 1.0;
  28716. /**
  28717. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28718. * for per-pixel control over specular intensity.
  28719. *
  28720. * @type {?Texture}
  28721. * @default null
  28722. */
  28723. this.specularIntensityMap = null;
  28724. /**
  28725. * Tints the specular reflection at normal incidence for non-metals only.
  28726. *
  28727. * @type {Color}
  28728. * @default (1,1,1)
  28729. */
  28730. this.specularColor = new Color( 1, 1, 1 );
  28731. /**
  28732. * The RGB channels of this texture are multiplied against `specularColor`,
  28733. * for per-pixel control over specular color.
  28734. *
  28735. * @type {?Texture}
  28736. * @default null
  28737. */
  28738. this.specularColorMap = null;
  28739. this._anisotropy = 0;
  28740. this._clearcoat = 0;
  28741. this._dispersion = 0;
  28742. this._iridescence = 0;
  28743. this._sheen = 0.0;
  28744. this._transmission = 0;
  28745. this.setValues( parameters );
  28746. }
  28747. /**
  28748. * The anisotropy strength, from `0.0` to `1.0`.
  28749. *
  28750. * @type {number}
  28751. * @default 0
  28752. */
  28753. get anisotropy() {
  28754. return this._anisotropy;
  28755. }
  28756. set anisotropy( value ) {
  28757. if ( this._anisotropy > 0 !== value > 0 ) {
  28758. this.version ++;
  28759. }
  28760. this._anisotropy = value;
  28761. }
  28762. /**
  28763. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28764. * clear coat related properties to enable multilayer materials that have a
  28765. * thin translucent layer over the base layer.
  28766. *
  28767. * @type {number}
  28768. * @default 0
  28769. */
  28770. get clearcoat() {
  28771. return this._clearcoat;
  28772. }
  28773. set clearcoat( value ) {
  28774. if ( this._clearcoat > 0 !== value > 0 ) {
  28775. this.version ++;
  28776. }
  28777. this._clearcoat = value;
  28778. }
  28779. /**
  28780. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28781. * the surface and the viewer, from `0.0` to `1.0`.
  28782. *
  28783. * @type {number}
  28784. * @default 0
  28785. */
  28786. get iridescence() {
  28787. return this._iridescence;
  28788. }
  28789. set iridescence( value ) {
  28790. if ( this._iridescence > 0 !== value > 0 ) {
  28791. this.version ++;
  28792. }
  28793. this._iridescence = value;
  28794. }
  28795. /**
  28796. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28797. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28798. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28799. *
  28800. * @type {number}
  28801. * @default 0
  28802. */
  28803. get dispersion() {
  28804. return this._dispersion;
  28805. }
  28806. set dispersion( value ) {
  28807. if ( this._dispersion > 0 !== value > 0 ) {
  28808. this.version ++;
  28809. }
  28810. this._dispersion = value;
  28811. }
  28812. /**
  28813. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28814. *
  28815. * @type {number}
  28816. * @default 0
  28817. */
  28818. get sheen() {
  28819. return this._sheen;
  28820. }
  28821. set sheen( value ) {
  28822. if ( this._sheen > 0 !== value > 0 ) {
  28823. this.version ++;
  28824. }
  28825. this._sheen = value;
  28826. }
  28827. /**
  28828. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28829. *
  28830. * Thin, transparent or semitransparent, plastic or glass materials remain
  28831. * largely reflective even if they are fully transmissive. The transmission
  28832. * property can be used to model these materials.
  28833. *
  28834. * When transmission is non-zero, `opacity` should be set to `1`.
  28835. *
  28836. * @type {number}
  28837. * @default 0
  28838. */
  28839. get transmission() {
  28840. return this._transmission;
  28841. }
  28842. set transmission( value ) {
  28843. if ( this._transmission > 0 !== value > 0 ) {
  28844. this.version ++;
  28845. }
  28846. this._transmission = value;
  28847. }
  28848. copy( source ) {
  28849. super.copy( source );
  28850. this.defines = {
  28851. 'STANDARD': '',
  28852. 'PHYSICAL': ''
  28853. };
  28854. this.anisotropy = source.anisotropy;
  28855. this.anisotropyRotation = source.anisotropyRotation;
  28856. this.anisotropyMap = source.anisotropyMap;
  28857. this.clearcoat = source.clearcoat;
  28858. this.clearcoatMap = source.clearcoatMap;
  28859. this.clearcoatRoughness = source.clearcoatRoughness;
  28860. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28861. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28862. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28863. this.dispersion = source.dispersion;
  28864. this.ior = source.ior;
  28865. this.iridescence = source.iridescence;
  28866. this.iridescenceMap = source.iridescenceMap;
  28867. this.iridescenceIOR = source.iridescenceIOR;
  28868. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28869. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28870. this.sheen = source.sheen;
  28871. this.sheenColor.copy( source.sheenColor );
  28872. this.sheenColorMap = source.sheenColorMap;
  28873. this.sheenRoughness = source.sheenRoughness;
  28874. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28875. this.transmission = source.transmission;
  28876. this.transmissionMap = source.transmissionMap;
  28877. this.thickness = source.thickness;
  28878. this.thicknessMap = source.thicknessMap;
  28879. this.attenuationDistance = source.attenuationDistance;
  28880. this.attenuationColor.copy( source.attenuationColor );
  28881. this.specularIntensity = source.specularIntensity;
  28882. this.specularIntensityMap = source.specularIntensityMap;
  28883. this.specularColor.copy( source.specularColor );
  28884. this.specularColorMap = source.specularColorMap;
  28885. return this;
  28886. }
  28887. }
  28888. /**
  28889. * A material for shiny surfaces with specular highlights.
  28890. *
  28891. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28892. * model for calculating reflectance. Unlike the Lambertian model used in the
  28893. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28894. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28895. *
  28896. * Performance will generally be greater when using this material over the
  28897. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28898. * some graphical accuracy.
  28899. *
  28900. * @augments Material
  28901. * @demo scenes/material-browser.html#MeshPhongMaterial
  28902. */
  28903. class MeshPhongMaterial extends Material {
  28904. /**
  28905. * Constructs a new mesh phong material.
  28906. *
  28907. * @param {Object} [parameters] - An object with one or more properties
  28908. * defining the material's appearance. Any property of the material
  28909. * (including any property from inherited materials) can be passed
  28910. * in here. Color values can be passed any type of value accepted
  28911. * by {@link Color#set}.
  28912. */
  28913. constructor( parameters ) {
  28914. super();
  28915. /**
  28916. * This flag can be used for type testing.
  28917. *
  28918. * @type {boolean}
  28919. * @readonly
  28920. * @default true
  28921. */
  28922. this.isMeshPhongMaterial = true;
  28923. this.type = 'MeshPhongMaterial';
  28924. /**
  28925. * Color of the material.
  28926. *
  28927. * @type {Color}
  28928. * @default (1,1,1)
  28929. */
  28930. this.color = new Color( 0xffffff ); // diffuse
  28931. /**
  28932. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28933. *
  28934. * This defines how shiny the material is and the color of its shine.
  28935. *
  28936. * @type {Color}
  28937. */
  28938. this.specular = new Color( 0x111111 );
  28939. /**
  28940. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28941. *
  28942. * @type {number}
  28943. * @default 30
  28944. */
  28945. this.shininess = 30;
  28946. /**
  28947. * The color map. May optionally include an alpha channel, typically combined
  28948. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28949. * color is modulated by the diffuse `color`.
  28950. *
  28951. * @type {?Texture}
  28952. * @default null
  28953. */
  28954. this.map = null;
  28955. /**
  28956. * The light map. Requires a second set of UVs.
  28957. *
  28958. * @type {?Texture}
  28959. * @default null
  28960. */
  28961. this.lightMap = null;
  28962. /**
  28963. * Intensity of the baked light.
  28964. *
  28965. * @type {number}
  28966. * @default 1
  28967. */
  28968. this.lightMapIntensity = 1.0;
  28969. /**
  28970. * The red channel of this texture is used as the ambient occlusion map.
  28971. * Requires a second set of UVs.
  28972. *
  28973. * @type {?Texture}
  28974. * @default null
  28975. */
  28976. this.aoMap = null;
  28977. /**
  28978. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28979. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28980. * red channel is also `1`, ambient light is fully occluded on a surface.
  28981. *
  28982. * @type {number}
  28983. * @default 1
  28984. */
  28985. this.aoMapIntensity = 1.0;
  28986. /**
  28987. * Emissive (light) color of the material, essentially a solid color
  28988. * unaffected by other lighting.
  28989. *
  28990. * @type {Color}
  28991. * @default (0,0,0)
  28992. */
  28993. this.emissive = new Color( 0x000000 );
  28994. /**
  28995. * Intensity of the emissive light. Modulates the emissive color.
  28996. *
  28997. * @type {number}
  28998. * @default 1
  28999. */
  29000. this.emissiveIntensity = 1.0;
  29001. /**
  29002. * Set emissive (glow) map. The emissive map color is modulated by the
  29003. * emissive color and the emissive intensity. If you have an emissive map,
  29004. * be sure to set the emissive color to something other than black.
  29005. *
  29006. * @type {?Texture}
  29007. * @default null
  29008. */
  29009. this.emissiveMap = null;
  29010. /**
  29011. * The texture to create a bump map. The black and white values map to the
  29012. * perceived depth in relation to the lights. Bump doesn't actually affect
  29013. * the geometry of the object, only the lighting. If a normal map is defined
  29014. * this will be ignored.
  29015. *
  29016. * @type {?Texture}
  29017. * @default null
  29018. */
  29019. this.bumpMap = null;
  29020. /**
  29021. * How much the bump map affects the material. Typical range is `[0,1]`.
  29022. *
  29023. * @type {number}
  29024. * @default 1
  29025. */
  29026. this.bumpScale = 1;
  29027. /**
  29028. * The texture to create a normal map. The RGB values affect the surface
  29029. * normal for each pixel fragment and change the way the color is lit. Normal
  29030. * maps do not change the actual shape of the surface, only the lighting. In
  29031. * case the material has a normal map authored using the left handed
  29032. * convention, the `y` component of `normalScale` should be negated to compensate
  29033. * for the different handedness.
  29034. *
  29035. * @type {?Texture}
  29036. * @default null
  29037. */
  29038. this.normalMap = null;
  29039. /**
  29040. * The type of normal map.
  29041. *
  29042. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29043. * @default TangentSpaceNormalMap
  29044. */
  29045. this.normalMapType = TangentSpaceNormalMap;
  29046. /**
  29047. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29048. *
  29049. * @type {Vector2}
  29050. * @default (1,1)
  29051. */
  29052. this.normalScale = new Vector2( 1, 1 );
  29053. /**
  29054. * The displacement map affects the position of the mesh's vertices. Unlike
  29055. * other maps which only affect the light and shade of the material the
  29056. * displaced vertices can cast shadows, block other objects, and otherwise
  29057. * act as real geometry. The displacement texture is an image where the value
  29058. * of each pixel (white being the highest) is mapped against, and
  29059. * repositions, the vertices of the mesh.
  29060. *
  29061. * @type {?Texture}
  29062. * @default null
  29063. */
  29064. this.displacementMap = null;
  29065. /**
  29066. * How much the displacement map affects the mesh (where black is no
  29067. * displacement, and white is maximum displacement). Without a displacement
  29068. * map set, this value is not applied.
  29069. *
  29070. * @type {number}
  29071. * @default 0
  29072. */
  29073. this.displacementScale = 1;
  29074. /**
  29075. * The offset of the displacement map's values on the mesh's vertices.
  29076. * The bias is added to the scaled sample of the displacement map.
  29077. * Without a displacement map set, this value is not applied.
  29078. *
  29079. * @type {number}
  29080. * @default 0
  29081. */
  29082. this.displacementBias = 0;
  29083. /**
  29084. * The specular map value affects both how much the specular surface
  29085. * highlight contributes and how much of the environment map affects the
  29086. * surface.
  29087. *
  29088. * @type {?Texture}
  29089. * @default null
  29090. */
  29091. this.specularMap = null;
  29092. /**
  29093. * The alpha map is a grayscale texture that controls the opacity across the
  29094. * surface (black: fully transparent; white: fully opaque).
  29095. *
  29096. * Only the color of the texture is used, ignoring the alpha channel if one
  29097. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29098. * when sampling this texture due to the extra bit of precision provided for
  29099. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29100. * luminance/alpha textures will also still work as expected.
  29101. *
  29102. * @type {?Texture}
  29103. * @default null
  29104. */
  29105. this.alphaMap = null;
  29106. /**
  29107. * The environment map.
  29108. *
  29109. * @type {?Texture}
  29110. * @default null
  29111. */
  29112. this.envMap = null;
  29113. /**
  29114. * The rotation of the environment map in radians.
  29115. *
  29116. * @type {Euler}
  29117. * @default (0,0,0)
  29118. */
  29119. this.envMapRotation = new Euler();
  29120. /**
  29121. * How to combine the result of the surface's color with the environment map, if any.
  29122. *
  29123. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29124. * blend between the two colors.
  29125. *
  29126. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29127. * @default MultiplyOperation
  29128. */
  29129. this.combine = MultiplyOperation;
  29130. /**
  29131. * How much the environment map affects the surface.
  29132. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29133. *
  29134. * @type {number}
  29135. * @default 1
  29136. */
  29137. this.reflectivity = 1;
  29138. /**
  29139. * Scales the effect of the environment map by multiplying its color.
  29140. *
  29141. * @type {number}
  29142. * @default 1
  29143. */
  29144. this.envMapIntensity = 1.0;
  29145. /**
  29146. * The index of refraction (IOR) of air (approximately 1) divided by the
  29147. * index of refraction of the material. It is used with environment mapping
  29148. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29149. * The refraction ratio should not exceed `1`.
  29150. *
  29151. * @type {number}
  29152. * @default 0.98
  29153. */
  29154. this.refractionRatio = 0.98;
  29155. /**
  29156. * Renders the geometry as a wireframe.
  29157. *
  29158. * @type {boolean}
  29159. * @default false
  29160. */
  29161. this.wireframe = false;
  29162. /**
  29163. * Controls the thickness of the wireframe.
  29164. *
  29165. * Can only be used with {@link SVGRenderer}.
  29166. *
  29167. * @type {number}
  29168. * @default 1
  29169. */
  29170. this.wireframeLinewidth = 1;
  29171. /**
  29172. * Defines appearance of wireframe ends.
  29173. *
  29174. * Can only be used with {@link SVGRenderer}.
  29175. *
  29176. * @type {('round'|'bevel'|'miter')}
  29177. * @default 'round'
  29178. */
  29179. this.wireframeLinecap = 'round';
  29180. /**
  29181. * Defines appearance of wireframe joints.
  29182. *
  29183. * Can only be used with {@link SVGRenderer}.
  29184. *
  29185. * @type {('round'|'bevel'|'miter')}
  29186. * @default 'round'
  29187. */
  29188. this.wireframeLinejoin = 'round';
  29189. /**
  29190. * Whether the material is rendered with flat shading or not.
  29191. *
  29192. * @type {boolean}
  29193. * @default false
  29194. */
  29195. this.flatShading = false;
  29196. /**
  29197. * Whether the material is affected by fog or not.
  29198. *
  29199. * @type {boolean}
  29200. * @default true
  29201. */
  29202. this.fog = true;
  29203. this.setValues( parameters );
  29204. }
  29205. copy( source ) {
  29206. super.copy( source );
  29207. this.color.copy( source.color );
  29208. this.specular.copy( source.specular );
  29209. this.shininess = source.shininess;
  29210. this.map = source.map;
  29211. this.lightMap = source.lightMap;
  29212. this.lightMapIntensity = source.lightMapIntensity;
  29213. this.aoMap = source.aoMap;
  29214. this.aoMapIntensity = source.aoMapIntensity;
  29215. this.emissive.copy( source.emissive );
  29216. this.emissiveMap = source.emissiveMap;
  29217. this.emissiveIntensity = source.emissiveIntensity;
  29218. this.bumpMap = source.bumpMap;
  29219. this.bumpScale = source.bumpScale;
  29220. this.normalMap = source.normalMap;
  29221. this.normalMapType = source.normalMapType;
  29222. this.normalScale.copy( source.normalScale );
  29223. this.displacementMap = source.displacementMap;
  29224. this.displacementScale = source.displacementScale;
  29225. this.displacementBias = source.displacementBias;
  29226. this.specularMap = source.specularMap;
  29227. this.alphaMap = source.alphaMap;
  29228. this.envMap = source.envMap;
  29229. this.envMapRotation.copy( source.envMapRotation );
  29230. this.combine = source.combine;
  29231. this.reflectivity = source.reflectivity;
  29232. this.envMapIntensity = source.envMapIntensity;
  29233. this.refractionRatio = source.refractionRatio;
  29234. this.wireframe = source.wireframe;
  29235. this.wireframeLinewidth = source.wireframeLinewidth;
  29236. this.wireframeLinecap = source.wireframeLinecap;
  29237. this.wireframeLinejoin = source.wireframeLinejoin;
  29238. this.flatShading = source.flatShading;
  29239. this.fog = source.fog;
  29240. return this;
  29241. }
  29242. }
  29243. /**
  29244. * A material implementing toon shading.
  29245. *
  29246. * @augments Material
  29247. * @demo scenes/material-browser.html#MeshToonMaterial
  29248. */
  29249. class MeshToonMaterial extends Material {
  29250. /**
  29251. * Constructs a new mesh toon material.
  29252. *
  29253. * @param {Object} [parameters] - An object with one or more properties
  29254. * defining the material's appearance. Any property of the material
  29255. * (including any property from inherited materials) can be passed
  29256. * in here. Color values can be passed any type of value accepted
  29257. * by {@link Color#set}.
  29258. */
  29259. constructor( parameters ) {
  29260. super();
  29261. /**
  29262. * This flag can be used for type testing.
  29263. *
  29264. * @type {boolean}
  29265. * @readonly
  29266. * @default true
  29267. */
  29268. this.isMeshToonMaterial = true;
  29269. this.defines = { 'TOON': '' };
  29270. this.type = 'MeshToonMaterial';
  29271. /**
  29272. * Color of the material.
  29273. *
  29274. * @type {Color}
  29275. * @default (1,1,1)
  29276. */
  29277. this.color = new Color( 0xffffff );
  29278. /**
  29279. * The color map. May optionally include an alpha channel, typically combined
  29280. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29281. * color is modulated by the diffuse `color`.
  29282. *
  29283. * @type {?Texture}
  29284. * @default null
  29285. */
  29286. this.map = null;
  29287. /**
  29288. * Gradient map for toon shading. It's required to set
  29289. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29290. * when using this type of texture.
  29291. *
  29292. * @type {?Texture}
  29293. * @default null
  29294. */
  29295. this.gradientMap = null;
  29296. /**
  29297. * The light map. Requires a second set of UVs.
  29298. *
  29299. * @type {?Texture}
  29300. * @default null
  29301. */
  29302. this.lightMap = null;
  29303. /**
  29304. * Intensity of the baked light.
  29305. *
  29306. * @type {number}
  29307. * @default 1
  29308. */
  29309. this.lightMapIntensity = 1.0;
  29310. /**
  29311. * The red channel of this texture is used as the ambient occlusion map.
  29312. * Requires a second set of UVs.
  29313. *
  29314. * @type {?Texture}
  29315. * @default null
  29316. */
  29317. this.aoMap = null;
  29318. /**
  29319. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29320. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29321. * red channel is also `1`, ambient light is fully occluded on a surface.
  29322. *
  29323. * @type {number}
  29324. * @default 1
  29325. */
  29326. this.aoMapIntensity = 1.0;
  29327. /**
  29328. * Emissive (light) color of the material, essentially a solid color
  29329. * unaffected by other lighting.
  29330. *
  29331. * @type {Color}
  29332. * @default (0,0,0)
  29333. */
  29334. this.emissive = new Color( 0x000000 );
  29335. /**
  29336. * Intensity of the emissive light. Modulates the emissive color.
  29337. *
  29338. * @type {number}
  29339. * @default 1
  29340. */
  29341. this.emissiveIntensity = 1.0;
  29342. /**
  29343. * Set emissive (glow) map. The emissive map color is modulated by the
  29344. * emissive color and the emissive intensity. If you have an emissive map,
  29345. * be sure to set the emissive color to something other than black.
  29346. *
  29347. * @type {?Texture}
  29348. * @default null
  29349. */
  29350. this.emissiveMap = null;
  29351. /**
  29352. * The texture to create a bump map. The black and white values map to the
  29353. * perceived depth in relation to the lights. Bump doesn't actually affect
  29354. * the geometry of the object, only the lighting. If a normal map is defined
  29355. * this will be ignored.
  29356. *
  29357. * @type {?Texture}
  29358. * @default null
  29359. */
  29360. this.bumpMap = null;
  29361. /**
  29362. * How much the bump map affects the material. Typical range is `[0,1]`.
  29363. *
  29364. * @type {number}
  29365. * @default 1
  29366. */
  29367. this.bumpScale = 1;
  29368. /**
  29369. * The texture to create a normal map. The RGB values affect the surface
  29370. * normal for each pixel fragment and change the way the color is lit. Normal
  29371. * maps do not change the actual shape of the surface, only the lighting. In
  29372. * case the material has a normal map authored using the left handed
  29373. * convention, the `y` component of `normalScale` should be negated to compensate
  29374. * for the different handedness.
  29375. *
  29376. * @type {?Texture}
  29377. * @default null
  29378. */
  29379. this.normalMap = null;
  29380. /**
  29381. * The type of normal map.
  29382. *
  29383. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29384. * @default TangentSpaceNormalMap
  29385. */
  29386. this.normalMapType = TangentSpaceNormalMap;
  29387. /**
  29388. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29389. *
  29390. * @type {Vector2}
  29391. * @default (1,1)
  29392. */
  29393. this.normalScale = new Vector2( 1, 1 );
  29394. /**
  29395. * The displacement map affects the position of the mesh's vertices. Unlike
  29396. * other maps which only affect the light and shade of the material the
  29397. * displaced vertices can cast shadows, block other objects, and otherwise
  29398. * act as real geometry. The displacement texture is an image where the value
  29399. * of each pixel (white being the highest) is mapped against, and
  29400. * repositions, the vertices of the mesh.
  29401. *
  29402. * @type {?Texture}
  29403. * @default null
  29404. */
  29405. this.displacementMap = null;
  29406. /**
  29407. * How much the displacement map affects the mesh (where black is no
  29408. * displacement, and white is maximum displacement). Without a displacement
  29409. * map set, this value is not applied.
  29410. *
  29411. * @type {number}
  29412. * @default 0
  29413. */
  29414. this.displacementScale = 1;
  29415. /**
  29416. * The offset of the displacement map's values on the mesh's vertices.
  29417. * The bias is added to the scaled sample of the displacement map.
  29418. * Without a displacement map set, this value is not applied.
  29419. *
  29420. * @type {number}
  29421. * @default 0
  29422. */
  29423. this.displacementBias = 0;
  29424. /**
  29425. * The alpha map is a grayscale texture that controls the opacity across the
  29426. * surface (black: fully transparent; white: fully opaque).
  29427. *
  29428. * Only the color of the texture is used, ignoring the alpha channel if one
  29429. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29430. * when sampling this texture due to the extra bit of precision provided for
  29431. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29432. * luminance/alpha textures will also still work as expected.
  29433. *
  29434. * @type {?Texture}
  29435. * @default null
  29436. */
  29437. this.alphaMap = null;
  29438. /**
  29439. * Renders the geometry as a wireframe.
  29440. *
  29441. * @type {boolean}
  29442. * @default false
  29443. */
  29444. this.wireframe = false;
  29445. /**
  29446. * Controls the thickness of the wireframe.
  29447. *
  29448. * Can only be used with {@link SVGRenderer}.
  29449. *
  29450. * @type {number}
  29451. * @default 1
  29452. */
  29453. this.wireframeLinewidth = 1;
  29454. /**
  29455. * Defines appearance of wireframe ends.
  29456. *
  29457. * Can only be used with {@link SVGRenderer}.
  29458. *
  29459. * @type {('round'|'bevel'|'miter')}
  29460. * @default 'round'
  29461. */
  29462. this.wireframeLinecap = 'round';
  29463. /**
  29464. * Defines appearance of wireframe joints.
  29465. *
  29466. * Can only be used with {@link SVGRenderer}.
  29467. *
  29468. * @type {('round'|'bevel'|'miter')}
  29469. * @default 'round'
  29470. */
  29471. this.wireframeLinejoin = 'round';
  29472. /**
  29473. * Whether the material is affected by fog or not.
  29474. *
  29475. * @type {boolean}
  29476. * @default true
  29477. */
  29478. this.fog = true;
  29479. this.setValues( parameters );
  29480. }
  29481. copy( source ) {
  29482. super.copy( source );
  29483. this.color.copy( source.color );
  29484. this.map = source.map;
  29485. this.gradientMap = source.gradientMap;
  29486. this.lightMap = source.lightMap;
  29487. this.lightMapIntensity = source.lightMapIntensity;
  29488. this.aoMap = source.aoMap;
  29489. this.aoMapIntensity = source.aoMapIntensity;
  29490. this.emissive.copy( source.emissive );
  29491. this.emissiveMap = source.emissiveMap;
  29492. this.emissiveIntensity = source.emissiveIntensity;
  29493. this.bumpMap = source.bumpMap;
  29494. this.bumpScale = source.bumpScale;
  29495. this.normalMap = source.normalMap;
  29496. this.normalMapType = source.normalMapType;
  29497. this.normalScale.copy( source.normalScale );
  29498. this.displacementMap = source.displacementMap;
  29499. this.displacementScale = source.displacementScale;
  29500. this.displacementBias = source.displacementBias;
  29501. this.alphaMap = source.alphaMap;
  29502. this.wireframe = source.wireframe;
  29503. this.wireframeLinewidth = source.wireframeLinewidth;
  29504. this.wireframeLinecap = source.wireframeLinecap;
  29505. this.wireframeLinejoin = source.wireframeLinejoin;
  29506. this.fog = source.fog;
  29507. return this;
  29508. }
  29509. }
  29510. /**
  29511. * A material that maps the normal vectors to RGB colors.
  29512. *
  29513. * @augments Material
  29514. * @demo scenes/material-browser.html#MeshNormalMaterial
  29515. */
  29516. class MeshNormalMaterial extends Material {
  29517. /**
  29518. * Constructs a new mesh normal material.
  29519. *
  29520. * @param {Object} [parameters] - An object with one or more properties
  29521. * defining the material's appearance. Any property of the material
  29522. * (including any property from inherited materials) can be passed
  29523. * in here. Color values can be passed any type of value accepted
  29524. * by {@link Color#set}.
  29525. */
  29526. constructor( parameters ) {
  29527. super();
  29528. /**
  29529. * This flag can be used for type testing.
  29530. *
  29531. * @type {boolean}
  29532. * @readonly
  29533. * @default true
  29534. */
  29535. this.isMeshNormalMaterial = true;
  29536. this.type = 'MeshNormalMaterial';
  29537. /**
  29538. * The texture to create a bump map. The black and white values map to the
  29539. * perceived depth in relation to the lights. Bump doesn't actually affect
  29540. * the geometry of the object, only the lighting. If a normal map is defined
  29541. * this will be ignored.
  29542. *
  29543. * @type {?Texture}
  29544. * @default null
  29545. */
  29546. this.bumpMap = null;
  29547. /**
  29548. * How much the bump map affects the material. Typical range is `[0,1]`.
  29549. *
  29550. * @type {number}
  29551. * @default 1
  29552. */
  29553. this.bumpScale = 1;
  29554. /**
  29555. * The texture to create a normal map. The RGB values affect the surface
  29556. * normal for each pixel fragment and change the way the color is lit. Normal
  29557. * maps do not change the actual shape of the surface, only the lighting. In
  29558. * case the material has a normal map authored using the left handed
  29559. * convention, the `y` component of `normalScale` should be negated to compensate
  29560. * for the different handedness.
  29561. *
  29562. * @type {?Texture}
  29563. * @default null
  29564. */
  29565. this.normalMap = null;
  29566. /**
  29567. * The type of normal map.
  29568. *
  29569. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29570. * @default TangentSpaceNormalMap
  29571. */
  29572. this.normalMapType = TangentSpaceNormalMap;
  29573. /**
  29574. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29575. *
  29576. * @type {Vector2}
  29577. * @default (1,1)
  29578. */
  29579. this.normalScale = new Vector2( 1, 1 );
  29580. /**
  29581. * The displacement map affects the position of the mesh's vertices. Unlike
  29582. * other maps which only affect the light and shade of the material the
  29583. * displaced vertices can cast shadows, block other objects, and otherwise
  29584. * act as real geometry. The displacement texture is an image where the value
  29585. * of each pixel (white being the highest) is mapped against, and
  29586. * repositions, the vertices of the mesh.
  29587. *
  29588. * @type {?Texture}
  29589. * @default null
  29590. */
  29591. this.displacementMap = null;
  29592. /**
  29593. * How much the displacement map affects the mesh (where black is no
  29594. * displacement, and white is maximum displacement). Without a displacement
  29595. * map set, this value is not applied.
  29596. *
  29597. * @type {number}
  29598. * @default 0
  29599. */
  29600. this.displacementScale = 1;
  29601. /**
  29602. * The offset of the displacement map's values on the mesh's vertices.
  29603. * The bias is added to the scaled sample of the displacement map.
  29604. * Without a displacement map set, this value is not applied.
  29605. *
  29606. * @type {number}
  29607. * @default 0
  29608. */
  29609. this.displacementBias = 0;
  29610. /**
  29611. * Renders the geometry as a wireframe.
  29612. *
  29613. * @type {boolean}
  29614. * @default false
  29615. */
  29616. this.wireframe = false;
  29617. /**
  29618. * Controls the thickness of the wireframe.
  29619. *
  29620. * WebGL and WebGPU ignore this property and always render
  29621. * 1 pixel wide lines.
  29622. *
  29623. * @type {number}
  29624. * @default 1
  29625. */
  29626. this.wireframeLinewidth = 1;
  29627. /**
  29628. * Whether the material is rendered with flat shading or not.
  29629. *
  29630. * @type {boolean}
  29631. * @default false
  29632. */
  29633. this.flatShading = false;
  29634. this.setValues( parameters );
  29635. }
  29636. copy( source ) {
  29637. super.copy( source );
  29638. this.bumpMap = source.bumpMap;
  29639. this.bumpScale = source.bumpScale;
  29640. this.normalMap = source.normalMap;
  29641. this.normalMapType = source.normalMapType;
  29642. this.normalScale.copy( source.normalScale );
  29643. this.displacementMap = source.displacementMap;
  29644. this.displacementScale = source.displacementScale;
  29645. this.displacementBias = source.displacementBias;
  29646. this.wireframe = source.wireframe;
  29647. this.wireframeLinewidth = source.wireframeLinewidth;
  29648. this.flatShading = source.flatShading;
  29649. return this;
  29650. }
  29651. }
  29652. /**
  29653. * A material for non-shiny surfaces, without specular highlights.
  29654. *
  29655. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29656. * model for calculating reflectance. This can simulate some surfaces (such
  29657. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29658. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29659. * shading.
  29660. *
  29661. * Due to the simplicity of the reflectance and illumination models,
  29662. * performance will be greater when using this material over the
  29663. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29664. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29665. *
  29666. * @augments Material
  29667. * @demo scenes/material-browser.html#MeshLambertMaterial
  29668. */
  29669. class MeshLambertMaterial extends Material {
  29670. /**
  29671. * Constructs a new mesh lambert material.
  29672. *
  29673. * @param {Object} [parameters] - An object with one or more properties
  29674. * defining the material's appearance. Any property of the material
  29675. * (including any property from inherited materials) can be passed
  29676. * in here. Color values can be passed any type of value accepted
  29677. * by {@link Color#set}.
  29678. */
  29679. constructor( parameters ) {
  29680. super();
  29681. /**
  29682. * This flag can be used for type testing.
  29683. *
  29684. * @type {boolean}
  29685. * @readonly
  29686. * @default true
  29687. */
  29688. this.isMeshLambertMaterial = true;
  29689. this.type = 'MeshLambertMaterial';
  29690. /**
  29691. * Color of the material.
  29692. *
  29693. * @type {Color}
  29694. * @default (1,1,1)
  29695. */
  29696. this.color = new Color( 0xffffff ); // diffuse
  29697. /**
  29698. * The color map. May optionally include an alpha channel, typically combined
  29699. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29700. * color is modulated by the diffuse `color`.
  29701. *
  29702. * @type {?Texture}
  29703. * @default null
  29704. */
  29705. this.map = null;
  29706. /**
  29707. * The light map. Requires a second set of UVs.
  29708. *
  29709. * @type {?Texture}
  29710. * @default null
  29711. */
  29712. this.lightMap = null;
  29713. /**
  29714. * Intensity of the baked light.
  29715. *
  29716. * @type {number}
  29717. * @default 1
  29718. */
  29719. this.lightMapIntensity = 1.0;
  29720. /**
  29721. * The red channel of this texture is used as the ambient occlusion map.
  29722. * Requires a second set of UVs.
  29723. *
  29724. * @type {?Texture}
  29725. * @default null
  29726. */
  29727. this.aoMap = null;
  29728. /**
  29729. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29730. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29731. * red channel is also `1`, ambient light is fully occluded on a surface.
  29732. *
  29733. * @type {number}
  29734. * @default 1
  29735. */
  29736. this.aoMapIntensity = 1.0;
  29737. /**
  29738. * Emissive (light) color of the material, essentially a solid color
  29739. * unaffected by other lighting.
  29740. *
  29741. * @type {Color}
  29742. * @default (0,0,0)
  29743. */
  29744. this.emissive = new Color( 0x000000 );
  29745. /**
  29746. * Intensity of the emissive light. Modulates the emissive color.
  29747. *
  29748. * @type {number}
  29749. * @default 1
  29750. */
  29751. this.emissiveIntensity = 1.0;
  29752. /**
  29753. * Set emissive (glow) map. The emissive map color is modulated by the
  29754. * emissive color and the emissive intensity. If you have an emissive map,
  29755. * be sure to set the emissive color to something other than black.
  29756. *
  29757. * @type {?Texture}
  29758. * @default null
  29759. */
  29760. this.emissiveMap = null;
  29761. /**
  29762. * The texture to create a bump map. The black and white values map to the
  29763. * perceived depth in relation to the lights. Bump doesn't actually affect
  29764. * the geometry of the object, only the lighting. If a normal map is defined
  29765. * this will be ignored.
  29766. *
  29767. * @type {?Texture}
  29768. * @default null
  29769. */
  29770. this.bumpMap = null;
  29771. /**
  29772. * How much the bump map affects the material. Typical range is `[0,1]`.
  29773. *
  29774. * @type {number}
  29775. * @default 1
  29776. */
  29777. this.bumpScale = 1;
  29778. /**
  29779. * The texture to create a normal map. The RGB values affect the surface
  29780. * normal for each pixel fragment and change the way the color is lit. Normal
  29781. * maps do not change the actual shape of the surface, only the lighting. In
  29782. * case the material has a normal map authored using the left handed
  29783. * convention, the `y` component of `normalScale` should be negated to compensate
  29784. * for the different handedness.
  29785. *
  29786. * @type {?Texture}
  29787. * @default null
  29788. */
  29789. this.normalMap = null;
  29790. /**
  29791. * The type of normal map.
  29792. *
  29793. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29794. * @default TangentSpaceNormalMap
  29795. */
  29796. this.normalMapType = TangentSpaceNormalMap;
  29797. /**
  29798. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29799. *
  29800. * @type {Vector2}
  29801. * @default (1,1)
  29802. */
  29803. this.normalScale = new Vector2( 1, 1 );
  29804. /**
  29805. * The displacement map affects the position of the mesh's vertices. Unlike
  29806. * other maps which only affect the light and shade of the material the
  29807. * displaced vertices can cast shadows, block other objects, and otherwise
  29808. * act as real geometry. The displacement texture is an image where the value
  29809. * of each pixel (white being the highest) is mapped against, and
  29810. * repositions, the vertices of the mesh.
  29811. *
  29812. * @type {?Texture}
  29813. * @default null
  29814. */
  29815. this.displacementMap = null;
  29816. /**
  29817. * How much the displacement map affects the mesh (where black is no
  29818. * displacement, and white is maximum displacement). Without a displacement
  29819. * map set, this value is not applied.
  29820. *
  29821. * @type {number}
  29822. * @default 0
  29823. */
  29824. this.displacementScale = 1;
  29825. /**
  29826. * The offset of the displacement map's values on the mesh's vertices.
  29827. * The bias is added to the scaled sample of the displacement map.
  29828. * Without a displacement map set, this value is not applied.
  29829. *
  29830. * @type {number}
  29831. * @default 0
  29832. */
  29833. this.displacementBias = 0;
  29834. /**
  29835. * Specular map used by the material.
  29836. *
  29837. * @type {?Texture}
  29838. * @default null
  29839. */
  29840. this.specularMap = null;
  29841. /**
  29842. * The alpha map is a grayscale texture that controls the opacity across the
  29843. * surface (black: fully transparent; white: fully opaque).
  29844. *
  29845. * Only the color of the texture is used, ignoring the alpha channel if one
  29846. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29847. * when sampling this texture due to the extra bit of precision provided for
  29848. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29849. * luminance/alpha textures will also still work as expected.
  29850. *
  29851. * @type {?Texture}
  29852. * @default null
  29853. */
  29854. this.alphaMap = null;
  29855. /**
  29856. * The environment map.
  29857. *
  29858. * @type {?Texture}
  29859. * @default null
  29860. */
  29861. this.envMap = null;
  29862. /**
  29863. * The rotation of the environment map in radians.
  29864. *
  29865. * @type {Euler}
  29866. * @default (0,0,0)
  29867. */
  29868. this.envMapRotation = new Euler();
  29869. /**
  29870. * How to combine the result of the surface's color with the environment map, if any.
  29871. *
  29872. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29873. * blend between the two colors.
  29874. *
  29875. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29876. * @default MultiplyOperation
  29877. */
  29878. this.combine = MultiplyOperation;
  29879. /**
  29880. * How much the environment map affects the surface.
  29881. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29882. *
  29883. * @type {number}
  29884. * @default 1
  29885. */
  29886. this.reflectivity = 1;
  29887. /**
  29888. * Scales the effect of the environment map by multiplying its color.
  29889. *
  29890. * @type {number}
  29891. * @default 1
  29892. */
  29893. this.envMapIntensity = 1.0;
  29894. /**
  29895. * The index of refraction (IOR) of air (approximately 1) divided by the
  29896. * index of refraction of the material. It is used with environment mapping
  29897. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29898. * The refraction ratio should not exceed `1`.
  29899. *
  29900. * @type {number}
  29901. * @default 0.98
  29902. */
  29903. this.refractionRatio = 0.98;
  29904. /**
  29905. * Renders the geometry as a wireframe.
  29906. *
  29907. * @type {boolean}
  29908. * @default false
  29909. */
  29910. this.wireframe = false;
  29911. /**
  29912. * Controls the thickness of the wireframe.
  29913. *
  29914. * Can only be used with {@link SVGRenderer}.
  29915. *
  29916. * @type {number}
  29917. * @default 1
  29918. */
  29919. this.wireframeLinewidth = 1;
  29920. /**
  29921. * Defines appearance of wireframe ends.
  29922. *
  29923. * Can only be used with {@link SVGRenderer}.
  29924. *
  29925. * @type {('round'|'bevel'|'miter')}
  29926. * @default 'round'
  29927. */
  29928. this.wireframeLinecap = 'round';
  29929. /**
  29930. * Defines appearance of wireframe joints.
  29931. *
  29932. * Can only be used with {@link SVGRenderer}.
  29933. *
  29934. * @type {('round'|'bevel'|'miter')}
  29935. * @default 'round'
  29936. */
  29937. this.wireframeLinejoin = 'round';
  29938. /**
  29939. * Whether the material is rendered with flat shading or not.
  29940. *
  29941. * @type {boolean}
  29942. * @default false
  29943. */
  29944. this.flatShading = false;
  29945. /**
  29946. * Whether the material is affected by fog or not.
  29947. *
  29948. * @type {boolean}
  29949. * @default true
  29950. */
  29951. this.fog = true;
  29952. this.setValues( parameters );
  29953. }
  29954. copy( source ) {
  29955. super.copy( source );
  29956. this.color.copy( source.color );
  29957. this.map = source.map;
  29958. this.lightMap = source.lightMap;
  29959. this.lightMapIntensity = source.lightMapIntensity;
  29960. this.aoMap = source.aoMap;
  29961. this.aoMapIntensity = source.aoMapIntensity;
  29962. this.emissive.copy( source.emissive );
  29963. this.emissiveMap = source.emissiveMap;
  29964. this.emissiveIntensity = source.emissiveIntensity;
  29965. this.bumpMap = source.bumpMap;
  29966. this.bumpScale = source.bumpScale;
  29967. this.normalMap = source.normalMap;
  29968. this.normalMapType = source.normalMapType;
  29969. this.normalScale.copy( source.normalScale );
  29970. this.displacementMap = source.displacementMap;
  29971. this.displacementScale = source.displacementScale;
  29972. this.displacementBias = source.displacementBias;
  29973. this.specularMap = source.specularMap;
  29974. this.alphaMap = source.alphaMap;
  29975. this.envMap = source.envMap;
  29976. this.envMapRotation.copy( source.envMapRotation );
  29977. this.combine = source.combine;
  29978. this.reflectivity = source.reflectivity;
  29979. this.envMapIntensity = source.envMapIntensity;
  29980. this.refractionRatio = source.refractionRatio;
  29981. this.wireframe = source.wireframe;
  29982. this.wireframeLinewidth = source.wireframeLinewidth;
  29983. this.wireframeLinecap = source.wireframeLinecap;
  29984. this.wireframeLinejoin = source.wireframeLinejoin;
  29985. this.flatShading = source.flatShading;
  29986. this.fog = source.fog;
  29987. return this;
  29988. }
  29989. }
  29990. /**
  29991. * A material for drawing geometry by depth. Depth is based off of the camera
  29992. * near and far plane. White is nearest, black is farthest.
  29993. *
  29994. * @augments Material
  29995. * @demo scenes/material-browser.html#MeshDepthMaterial
  29996. */
  29997. class MeshDepthMaterial extends Material {
  29998. /**
  29999. * Constructs a new mesh depth material.
  30000. *
  30001. * @param {Object} [parameters] - An object with one or more properties
  30002. * defining the material's appearance. Any property of the material
  30003. * (including any property from inherited materials) can be passed
  30004. * in here. Color values can be passed any type of value accepted
  30005. * by {@link Color#set}.
  30006. */
  30007. constructor( parameters ) {
  30008. super();
  30009. /**
  30010. * This flag can be used for type testing.
  30011. *
  30012. * @type {boolean}
  30013. * @readonly
  30014. * @default true
  30015. */
  30016. this.isMeshDepthMaterial = true;
  30017. this.type = 'MeshDepthMaterial';
  30018. /**
  30019. * Type for depth packing.
  30020. *
  30021. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  30022. * @default BasicDepthPacking
  30023. */
  30024. this.depthPacking = BasicDepthPacking;
  30025. /**
  30026. * The color map. May optionally include an alpha channel, typically combined
  30027. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30028. *
  30029. * @type {?Texture}
  30030. * @default null
  30031. */
  30032. this.map = null;
  30033. /**
  30034. * The alpha map is a grayscale texture that controls the opacity across the
  30035. * surface (black: fully transparent; white: fully opaque).
  30036. *
  30037. * Only the color of the texture is used, ignoring the alpha channel if one
  30038. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30039. * when sampling this texture due to the extra bit of precision provided for
  30040. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30041. * luminance/alpha textures will also still work as expected.
  30042. *
  30043. * @type {?Texture}
  30044. * @default null
  30045. */
  30046. this.alphaMap = null;
  30047. /**
  30048. * The displacement map affects the position of the mesh's vertices. Unlike
  30049. * other maps which only affect the light and shade of the material the
  30050. * displaced vertices can cast shadows, block other objects, and otherwise
  30051. * act as real geometry. The displacement texture is an image where the value
  30052. * of each pixel (white being the highest) is mapped against, and
  30053. * repositions, the vertices of the mesh.
  30054. *
  30055. * @type {?Texture}
  30056. * @default null
  30057. */
  30058. this.displacementMap = null;
  30059. /**
  30060. * How much the displacement map affects the mesh (where black is no
  30061. * displacement, and white is maximum displacement). Without a displacement
  30062. * map set, this value is not applied.
  30063. *
  30064. * @type {number}
  30065. * @default 0
  30066. */
  30067. this.displacementScale = 1;
  30068. /**
  30069. * The offset of the displacement map's values on the mesh's vertices.
  30070. * The bias is added to the scaled sample of the displacement map.
  30071. * Without a displacement map set, this value is not applied.
  30072. *
  30073. * @type {number}
  30074. * @default 0
  30075. */
  30076. this.displacementBias = 0;
  30077. /**
  30078. * Renders the geometry as a wireframe.
  30079. *
  30080. * @type {boolean}
  30081. * @default false
  30082. */
  30083. this.wireframe = false;
  30084. /**
  30085. * Controls the thickness of the wireframe.
  30086. *
  30087. * WebGL and WebGPU ignore this property and always render
  30088. * 1 pixel wide lines.
  30089. *
  30090. * @type {number}
  30091. * @default 1
  30092. */
  30093. this.wireframeLinewidth = 1;
  30094. this.setValues( parameters );
  30095. }
  30096. copy( source ) {
  30097. super.copy( source );
  30098. this.depthPacking = source.depthPacking;
  30099. this.map = source.map;
  30100. this.alphaMap = source.alphaMap;
  30101. this.displacementMap = source.displacementMap;
  30102. this.displacementScale = source.displacementScale;
  30103. this.displacementBias = source.displacementBias;
  30104. this.wireframe = source.wireframe;
  30105. this.wireframeLinewidth = source.wireframeLinewidth;
  30106. return this;
  30107. }
  30108. }
  30109. /**
  30110. * A material used internally for implementing shadow mapping with
  30111. * point lights.
  30112. *
  30113. * Can also be used to customize the shadow casting of an object by assigning
  30114. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30115. * The following examples demonstrates this approach in order to ensure
  30116. * transparent parts of objects do not cast shadows.
  30117. *
  30118. * @augments Material
  30119. */
  30120. class MeshDistanceMaterial extends Material {
  30121. /**
  30122. * Constructs a new mesh distance material.
  30123. *
  30124. * @param {Object} [parameters] - An object with one or more properties
  30125. * defining the material's appearance. Any property of the material
  30126. * (including any property from inherited materials) can be passed
  30127. * in here. Color values can be passed any type of value accepted
  30128. * by {@link Color#set}.
  30129. */
  30130. constructor( parameters ) {
  30131. super();
  30132. /**
  30133. * This flag can be used for type testing.
  30134. *
  30135. * @type {boolean}
  30136. * @readonly
  30137. * @default true
  30138. */
  30139. this.isMeshDistanceMaterial = true;
  30140. this.type = 'MeshDistanceMaterial';
  30141. /**
  30142. * The color map. May optionally include an alpha channel, typically combined
  30143. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30144. *
  30145. * @type {?Texture}
  30146. * @default null
  30147. */
  30148. this.map = null;
  30149. /**
  30150. * The alpha map is a grayscale texture that controls the opacity across the
  30151. * surface (black: fully transparent; white: fully opaque).
  30152. *
  30153. * Only the color of the texture is used, ignoring the alpha channel if one
  30154. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30155. * when sampling this texture due to the extra bit of precision provided for
  30156. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30157. * luminance/alpha textures will also still work as expected.
  30158. *
  30159. * @type {?Texture}
  30160. * @default null
  30161. */
  30162. this.alphaMap = null;
  30163. /**
  30164. * The displacement map affects the position of the mesh's vertices. Unlike
  30165. * other maps which only affect the light and shade of the material the
  30166. * displaced vertices can cast shadows, block other objects, and otherwise
  30167. * act as real geometry. The displacement texture is an image where the value
  30168. * of each pixel (white being the highest) is mapped against, and
  30169. * repositions, the vertices of the mesh.
  30170. *
  30171. * @type {?Texture}
  30172. * @default null
  30173. */
  30174. this.displacementMap = null;
  30175. /**
  30176. * How much the displacement map affects the mesh (where black is no
  30177. * displacement, and white is maximum displacement). Without a displacement
  30178. * map set, this value is not applied.
  30179. *
  30180. * @type {number}
  30181. * @default 0
  30182. */
  30183. this.displacementScale = 1;
  30184. /**
  30185. * The offset of the displacement map's values on the mesh's vertices.
  30186. * The bias is added to the scaled sample of the displacement map.
  30187. * Without a displacement map set, this value is not applied.
  30188. *
  30189. * @type {number}
  30190. * @default 0
  30191. */
  30192. this.displacementBias = 0;
  30193. this.setValues( parameters );
  30194. }
  30195. copy( source ) {
  30196. super.copy( source );
  30197. this.map = source.map;
  30198. this.alphaMap = source.alphaMap;
  30199. this.displacementMap = source.displacementMap;
  30200. this.displacementScale = source.displacementScale;
  30201. this.displacementBias = source.displacementBias;
  30202. return this;
  30203. }
  30204. }
  30205. /**
  30206. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30207. * material color and shading.
  30208. *
  30209. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30210. * baked lighting. It will cast a shadow onto an object that receives shadows
  30211. * (and shadow clipping works), but it will not self-shadow or receive
  30212. * shadows.
  30213. *
  30214. * @augments Material
  30215. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30216. */
  30217. class MeshMatcapMaterial extends Material {
  30218. /**
  30219. * Constructs a new mesh matcap material.
  30220. *
  30221. * @param {Object} [parameters] - An object with one or more properties
  30222. * defining the material's appearance. Any property of the material
  30223. * (including any property from inherited materials) can be passed
  30224. * in here. Color values can be passed any type of value accepted
  30225. * by {@link Color#set}.
  30226. */
  30227. constructor( parameters ) {
  30228. super();
  30229. /**
  30230. * This flag can be used for type testing.
  30231. *
  30232. * @type {boolean}
  30233. * @readonly
  30234. * @default true
  30235. */
  30236. this.isMeshMatcapMaterial = true;
  30237. this.defines = { 'MATCAP': '' };
  30238. this.type = 'MeshMatcapMaterial';
  30239. /**
  30240. * Color of the material.
  30241. *
  30242. * @type {Color}
  30243. * @default (1,1,1)
  30244. */
  30245. this.color = new Color( 0xffffff ); // diffuse
  30246. /**
  30247. * The matcap map.
  30248. *
  30249. * @type {?Texture}
  30250. * @default null
  30251. */
  30252. this.matcap = null;
  30253. /**
  30254. * The color map. May optionally include an alpha channel, typically combined
  30255. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30256. * color is modulated by the diffuse `color`.
  30257. *
  30258. * @type {?Texture}
  30259. * @default null
  30260. */
  30261. this.map = null;
  30262. /**
  30263. * The texture to create a bump map. The black and white values map to the
  30264. * perceived depth in relation to the lights. Bump doesn't actually affect
  30265. * the geometry of the object, only the lighting. If a normal map is defined
  30266. * this will be ignored.
  30267. *
  30268. * @type {?Texture}
  30269. * @default null
  30270. */
  30271. this.bumpMap = null;
  30272. /**
  30273. * How much the bump map affects the material. Typical range is `[0,1]`.
  30274. *
  30275. * @type {number}
  30276. * @default 1
  30277. */
  30278. this.bumpScale = 1;
  30279. /**
  30280. * The texture to create a normal map. The RGB values affect the surface
  30281. * normal for each pixel fragment and change the way the color is lit. Normal
  30282. * maps do not change the actual shape of the surface, only the lighting. In
  30283. * case the material has a normal map authored using the left handed
  30284. * convention, the `y` component of `normalScale` should be negated to compensate
  30285. * for the different handedness.
  30286. *
  30287. * @type {?Texture}
  30288. * @default null
  30289. */
  30290. this.normalMap = null;
  30291. /**
  30292. * The type of normal map.
  30293. *
  30294. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30295. * @default TangentSpaceNormalMap
  30296. */
  30297. this.normalMapType = TangentSpaceNormalMap;
  30298. /**
  30299. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30300. *
  30301. * @type {Vector2}
  30302. * @default (1,1)
  30303. */
  30304. this.normalScale = new Vector2( 1, 1 );
  30305. /**
  30306. * The displacement map affects the position of the mesh's vertices. Unlike
  30307. * other maps which only affect the light and shade of the material the
  30308. * displaced vertices can cast shadows, block other objects, and otherwise
  30309. * act as real geometry. The displacement texture is an image where the value
  30310. * of each pixel (white being the highest) is mapped against, and
  30311. * repositions, the vertices of the mesh.
  30312. *
  30313. * @type {?Texture}
  30314. * @default null
  30315. */
  30316. this.displacementMap = null;
  30317. /**
  30318. * How much the displacement map affects the mesh (where black is no
  30319. * displacement, and white is maximum displacement). Without a displacement
  30320. * map set, this value is not applied.
  30321. *
  30322. * @type {number}
  30323. * @default 0
  30324. */
  30325. this.displacementScale = 1;
  30326. /**
  30327. * The offset of the displacement map's values on the mesh's vertices.
  30328. * The bias is added to the scaled sample of the displacement map.
  30329. * Without a displacement map set, this value is not applied.
  30330. *
  30331. * @type {number}
  30332. * @default 0
  30333. */
  30334. this.displacementBias = 0;
  30335. /**
  30336. * The alpha map is a grayscale texture that controls the opacity across the
  30337. * surface (black: fully transparent; white: fully opaque).
  30338. *
  30339. * Only the color of the texture is used, ignoring the alpha channel if one
  30340. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30341. * when sampling this texture due to the extra bit of precision provided for
  30342. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30343. * luminance/alpha textures will also still work as expected.
  30344. *
  30345. * @type {?Texture}
  30346. * @default null
  30347. */
  30348. this.alphaMap = null;
  30349. /**
  30350. * Renders the geometry as a wireframe.
  30351. *
  30352. * @type {boolean}
  30353. * @default false
  30354. */
  30355. this.wireframe = false;
  30356. /**
  30357. * Controls the thickness of the wireframe.
  30358. *
  30359. * Can only be used with {@link SVGRenderer}.
  30360. *
  30361. * @type {number}
  30362. * @default 1
  30363. */
  30364. this.wireframeLinewidth = 1;
  30365. /**
  30366. * Whether the material is rendered with flat shading or not.
  30367. *
  30368. * @type {boolean}
  30369. * @default false
  30370. */
  30371. this.flatShading = false;
  30372. /**
  30373. * Whether the material is affected by fog or not.
  30374. *
  30375. * @type {boolean}
  30376. * @default true
  30377. */
  30378. this.fog = true;
  30379. this.setValues( parameters );
  30380. }
  30381. copy( source ) {
  30382. super.copy( source );
  30383. this.defines = { 'MATCAP': '' };
  30384. this.color.copy( source.color );
  30385. this.matcap = source.matcap;
  30386. this.map = source.map;
  30387. this.bumpMap = source.bumpMap;
  30388. this.bumpScale = source.bumpScale;
  30389. this.normalMap = source.normalMap;
  30390. this.normalMapType = source.normalMapType;
  30391. this.normalScale.copy( source.normalScale );
  30392. this.displacementMap = source.displacementMap;
  30393. this.displacementScale = source.displacementScale;
  30394. this.displacementBias = source.displacementBias;
  30395. this.alphaMap = source.alphaMap;
  30396. this.wireframe = source.wireframe;
  30397. this.wireframeLinewidth = source.wireframeLinewidth;
  30398. this.flatShading = source.flatShading;
  30399. this.fog = source.fog;
  30400. return this;
  30401. }
  30402. }
  30403. /**
  30404. * A material for rendering line primitives.
  30405. *
  30406. * Materials define the appearance of renderable 3D objects.
  30407. *
  30408. * ```js
  30409. * const material = new THREE.LineDashedMaterial( {
  30410. * color: 0xffffff,
  30411. * scale: 1,
  30412. * dashSize: 3,
  30413. * gapSize: 1,
  30414. * } );
  30415. * ```
  30416. *
  30417. * @augments LineBasicMaterial
  30418. */
  30419. class LineDashedMaterial extends LineBasicMaterial {
  30420. /**
  30421. * Constructs a new line dashed material.
  30422. *
  30423. * @param {Object} [parameters] - An object with one or more properties
  30424. * defining the material's appearance. Any property of the material
  30425. * (including any property from inherited materials) can be passed
  30426. * in here. Color values can be passed any type of value accepted
  30427. * by {@link Color#set}.
  30428. */
  30429. constructor( parameters ) {
  30430. super();
  30431. /**
  30432. * This flag can be used for type testing.
  30433. *
  30434. * @type {boolean}
  30435. * @readonly
  30436. * @default true
  30437. */
  30438. this.isLineDashedMaterial = true;
  30439. this.type = 'LineDashedMaterial';
  30440. /**
  30441. * The scale of the dashed part of a line.
  30442. *
  30443. * @type {number}
  30444. * @default 1
  30445. */
  30446. this.scale = 1;
  30447. /**
  30448. * The size of the dash. This is both the gap with the stroke.
  30449. *
  30450. * @type {number}
  30451. * @default 3
  30452. */
  30453. this.dashSize = 3;
  30454. /**
  30455. * The size of the gap.
  30456. *
  30457. * @type {number}
  30458. * @default 1
  30459. */
  30460. this.gapSize = 1;
  30461. this.setValues( parameters );
  30462. }
  30463. copy( source ) {
  30464. super.copy( source );
  30465. this.scale = source.scale;
  30466. this.dashSize = source.dashSize;
  30467. this.gapSize = source.gapSize;
  30468. return this;
  30469. }
  30470. }
  30471. /**
  30472. * Converts an array to a specific type.
  30473. *
  30474. * @param {TypedArray|Array} array - The array to convert.
  30475. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30476. * @return {TypedArray} The converted array.
  30477. */
  30478. function convertArray( array, type ) {
  30479. if ( ! array || array.constructor === type ) return array;
  30480. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30481. return new type( array ); // create typed array
  30482. }
  30483. return Array.prototype.slice.call( array ); // create Array
  30484. }
  30485. /**
  30486. * Returns an array by which times and values can be sorted.
  30487. *
  30488. * @param {Array<number>} times - The keyframe time values.
  30489. * @return {Array<number>} The array.
  30490. */
  30491. function getKeyframeOrder( times ) {
  30492. function compareTime( i, j ) {
  30493. return times[ i ] - times[ j ];
  30494. }
  30495. const n = times.length;
  30496. const result = new Array( n );
  30497. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30498. result.sort( compareTime );
  30499. return result;
  30500. }
  30501. /**
  30502. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30503. *
  30504. * @param {Array<number>} values - The values to sort.
  30505. * @param {number} stride - The stride.
  30506. * @param {Array<number>} order - The sort order.
  30507. * @return {Array<number>} The sorted values.
  30508. */
  30509. function sortedArray( values, stride, order ) {
  30510. const nValues = values.length;
  30511. const result = new values.constructor( nValues );
  30512. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30513. const srcOffset = order[ i ] * stride;
  30514. for ( let j = 0; j !== stride; ++ j ) {
  30515. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30516. }
  30517. }
  30518. return result;
  30519. }
  30520. /**
  30521. * Used for parsing AOS keyframe formats.
  30522. *
  30523. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30524. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30525. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30526. * @param {string} valuePropertyName - The name of the property to use.
  30527. */
  30528. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30529. let i = 1, key = jsonKeys[ 0 ];
  30530. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30531. key = jsonKeys[ i ++ ];
  30532. }
  30533. if ( key === undefined ) return; // no data
  30534. let value = key[ valuePropertyName ];
  30535. if ( value === undefined ) return; // no data
  30536. if ( Array.isArray( value ) ) {
  30537. do {
  30538. value = key[ valuePropertyName ];
  30539. if ( value !== undefined ) {
  30540. times.push( key.time );
  30541. values.push( ...value ); // push all elements
  30542. }
  30543. key = jsonKeys[ i ++ ];
  30544. } while ( key !== undefined );
  30545. } else if ( value.toArray !== undefined ) {
  30546. // ...assume THREE.Math-ish
  30547. do {
  30548. value = key[ valuePropertyName ];
  30549. if ( value !== undefined ) {
  30550. times.push( key.time );
  30551. value.toArray( values, values.length );
  30552. }
  30553. key = jsonKeys[ i ++ ];
  30554. } while ( key !== undefined );
  30555. } else {
  30556. // otherwise push as-is
  30557. do {
  30558. value = key[ valuePropertyName ];
  30559. if ( value !== undefined ) {
  30560. times.push( key.time );
  30561. values.push( value );
  30562. }
  30563. key = jsonKeys[ i ++ ];
  30564. } while ( key !== undefined );
  30565. }
  30566. }
  30567. /**
  30568. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30569. *
  30570. * @param {AnimationClip} sourceClip - The values to sort.
  30571. * @param {string} name - The name of the clip.
  30572. * @param {number} startFrame - The start frame.
  30573. * @param {number} endFrame - The end frame.
  30574. * @param {number} [fps=30] - The FPS.
  30575. * @return {AnimationClip} The new sub clip.
  30576. */
  30577. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30578. const clip = sourceClip.clone();
  30579. clip.name = name;
  30580. const tracks = [];
  30581. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30582. const track = clip.tracks[ i ];
  30583. const valueSize = track.getValueSize();
  30584. const times = [];
  30585. const values = [];
  30586. for ( let j = 0; j < track.times.length; ++ j ) {
  30587. const frame = track.times[ j ] * fps;
  30588. if ( frame < startFrame || frame >= endFrame ) continue;
  30589. times.push( track.times[ j ] );
  30590. for ( let k = 0; k < valueSize; ++ k ) {
  30591. values.push( track.values[ j * valueSize + k ] );
  30592. }
  30593. }
  30594. if ( times.length === 0 ) continue;
  30595. track.times = convertArray( times, track.times.constructor );
  30596. track.values = convertArray( values, track.values.constructor );
  30597. tracks.push( track );
  30598. }
  30599. clip.tracks = tracks;
  30600. // find minimum .times value across all tracks in the trimmed clip
  30601. let minStartTime = Infinity;
  30602. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30603. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30604. minStartTime = clip.tracks[ i ].times[ 0 ];
  30605. }
  30606. }
  30607. // shift all tracks such that clip begins at t=0
  30608. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30609. clip.tracks[ i ].shift( -1 * minStartTime );
  30610. }
  30611. clip.resetDuration();
  30612. return clip;
  30613. }
  30614. /**
  30615. * Converts the keyframes of the given animation clip to an additive format.
  30616. *
  30617. * @param {AnimationClip} targetClip - The clip to make additive.
  30618. * @param {number} [referenceFrame=0] - The reference frame.
  30619. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30620. * @param {number} [fps=30] - The FPS.
  30621. * @return {AnimationClip} The updated clip which is now additive.
  30622. */
  30623. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30624. if ( fps <= 0 ) fps = 30;
  30625. const numTracks = referenceClip.tracks.length;
  30626. const referenceTime = referenceFrame / fps;
  30627. // Make each track's values relative to the values at the reference frame
  30628. for ( let i = 0; i < numTracks; ++ i ) {
  30629. const referenceTrack = referenceClip.tracks[ i ];
  30630. const referenceTrackType = referenceTrack.ValueTypeName;
  30631. // Skip this track if it's non-numeric
  30632. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30633. // Find the track in the target clip whose name and type matches the reference track
  30634. const targetTrack = targetClip.tracks.find( function ( track ) {
  30635. return track.name === referenceTrack.name
  30636. && track.ValueTypeName === referenceTrackType;
  30637. } );
  30638. if ( targetTrack === undefined ) continue;
  30639. let referenceOffset = 0;
  30640. const referenceValueSize = referenceTrack.getValueSize();
  30641. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30642. referenceOffset = referenceValueSize / 3;
  30643. }
  30644. let targetOffset = 0;
  30645. const targetValueSize = targetTrack.getValueSize();
  30646. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30647. targetOffset = targetValueSize / 3;
  30648. }
  30649. const lastIndex = referenceTrack.times.length - 1;
  30650. let referenceValue;
  30651. // Find the value to subtract out of the track
  30652. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30653. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30654. const startIndex = referenceOffset;
  30655. const endIndex = referenceValueSize - referenceOffset;
  30656. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30657. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30658. // Reference frame is after the last keyframe, so just use the last keyframe
  30659. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30660. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30661. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30662. } else {
  30663. // Interpolate to the reference value
  30664. const interpolant = referenceTrack.createInterpolant();
  30665. const startIndex = referenceOffset;
  30666. const endIndex = referenceValueSize - referenceOffset;
  30667. interpolant.evaluate( referenceTime );
  30668. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30669. }
  30670. // Conjugate the quaternion
  30671. if ( referenceTrackType === 'quaternion' ) {
  30672. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30673. referenceQuat.toArray( referenceValue );
  30674. }
  30675. // Subtract the reference value from all of the track values
  30676. const numTimes = targetTrack.times.length;
  30677. for ( let j = 0; j < numTimes; ++ j ) {
  30678. const valueStart = j * targetValueSize + targetOffset;
  30679. if ( referenceTrackType === 'quaternion' ) {
  30680. // Multiply the conjugate for quaternion track types
  30681. Quaternion.multiplyQuaternionsFlat(
  30682. targetTrack.values,
  30683. valueStart,
  30684. referenceValue,
  30685. 0,
  30686. targetTrack.values,
  30687. valueStart
  30688. );
  30689. } else {
  30690. const valueEnd = targetValueSize - targetOffset * 2;
  30691. // Subtract each value for all other numeric track types
  30692. for ( let k = 0; k < valueEnd; ++ k ) {
  30693. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30694. }
  30695. }
  30696. }
  30697. }
  30698. targetClip.blendMode = AdditiveAnimationBlendMode;
  30699. return targetClip;
  30700. }
  30701. /**
  30702. * A class with various methods to assist with animations.
  30703. *
  30704. * @hideconstructor
  30705. */
  30706. class AnimationUtils {
  30707. /**
  30708. * Converts an array to a specific type
  30709. *
  30710. * @static
  30711. * @param {TypedArray|Array} array - The array to convert.
  30712. * @param {TypedArray.constructor} type - The constructor of a type array.
  30713. * @return {TypedArray} The converted array
  30714. */
  30715. static convertArray( array, type ) {
  30716. return convertArray( array, type );
  30717. }
  30718. /**
  30719. * Returns `true` if the given object is a typed array.
  30720. *
  30721. * @static
  30722. * @param {any} object - The object to check.
  30723. * @return {boolean} Whether the given object is a typed array.
  30724. */
  30725. static isTypedArray( object ) {
  30726. return isTypedArray( object );
  30727. }
  30728. /**
  30729. * Returns an array by which times and values can be sorted.
  30730. *
  30731. * @static
  30732. * @param {Array<number>} times - The keyframe time values.
  30733. * @return {Array<number>} The array.
  30734. */
  30735. static getKeyframeOrder( times ) {
  30736. return getKeyframeOrder( times );
  30737. }
  30738. /**
  30739. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30740. *
  30741. * @static
  30742. * @param {Array<number>} values - The values to sort.
  30743. * @param {number} stride - The stride.
  30744. * @param {Array<number>} order - The sort order.
  30745. * @return {Array<number>} The sorted values.
  30746. */
  30747. static sortedArray( values, stride, order ) {
  30748. return sortedArray( values, stride, order );
  30749. }
  30750. /**
  30751. * Used for parsing AOS keyframe formats.
  30752. *
  30753. * @static
  30754. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30755. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30756. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30757. * @param {string} valuePropertyName - The name of the property to use.
  30758. */
  30759. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30760. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30761. }
  30762. /**
  30763. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30764. *
  30765. * @static
  30766. * @param {AnimationClip} sourceClip - The values to sort.
  30767. * @param {string} name - The name of the clip.
  30768. * @param {number} startFrame - The start frame.
  30769. * @param {number} endFrame - The end frame.
  30770. * @param {number} [fps=30] - The FPS.
  30771. * @return {AnimationClip} The new sub clip.
  30772. */
  30773. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30774. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30775. }
  30776. /**
  30777. * Converts the keyframes of the given animation clip to an additive format.
  30778. *
  30779. * @static
  30780. * @param {AnimationClip} targetClip - The clip to make additive.
  30781. * @param {number} [referenceFrame=0] - The reference frame.
  30782. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30783. * @param {number} [fps=30] - The FPS.
  30784. * @return {AnimationClip} The updated clip which is now additive.
  30785. */
  30786. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30787. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30788. }
  30789. }
  30790. /**
  30791. * Abstract base class of interpolants over parametric samples.
  30792. *
  30793. * The parameter domain is one dimensional, typically the time or a path
  30794. * along a curve defined by the data.
  30795. *
  30796. * The sample values can have any dimensionality and derived classes may
  30797. * apply special interpretations to the data.
  30798. *
  30799. * This class provides the interval seek in a Template Method, deferring
  30800. * the actual interpolation to derived classes.
  30801. *
  30802. * Time complexity is O(1) for linear access crossing at most two points
  30803. * and O(log N) for random access, where N is the number of positions.
  30804. *
  30805. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30806. *
  30807. * @abstract
  30808. */
  30809. class Interpolant {
  30810. /**
  30811. * Constructs a new interpolant.
  30812. *
  30813. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30814. * @param {TypedArray} sampleValues - The sample values.
  30815. * @param {number} sampleSize - The sample size
  30816. * @param {TypedArray} [resultBuffer] - The result buffer.
  30817. */
  30818. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30819. /**
  30820. * The parameter positions.
  30821. *
  30822. * @type {TypedArray}
  30823. */
  30824. this.parameterPositions = parameterPositions;
  30825. /**
  30826. * A cache index.
  30827. *
  30828. * @private
  30829. * @type {number}
  30830. * @default 0
  30831. */
  30832. this._cachedIndex = 0;
  30833. /**
  30834. * The result buffer.
  30835. *
  30836. * @type {TypedArray}
  30837. */
  30838. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30839. /**
  30840. * The sample values.
  30841. *
  30842. * @type {TypedArray}
  30843. */
  30844. this.sampleValues = sampleValues;
  30845. /**
  30846. * The value size.
  30847. *
  30848. * @type {TypedArray}
  30849. */
  30850. this.valueSize = sampleSize;
  30851. /**
  30852. * The interpolation settings.
  30853. *
  30854. * @type {?Object}
  30855. * @default null
  30856. */
  30857. this.settings = null;
  30858. /**
  30859. * The default settings object.
  30860. *
  30861. * @type {Object}
  30862. */
  30863. this.DefaultSettings_ = {};
  30864. }
  30865. /**
  30866. * Evaluate the interpolant at position `t`.
  30867. *
  30868. * @param {number} t - The interpolation factor.
  30869. * @return {TypedArray} The result buffer.
  30870. */
  30871. evaluate( t ) {
  30872. const pp = this.parameterPositions;
  30873. let i1 = this._cachedIndex,
  30874. t1 = pp[ i1 ],
  30875. t0 = pp[ i1 - 1 ];
  30876. validate_interval: {
  30877. seek: {
  30878. let right;
  30879. linear_scan: {
  30880. //- See http://jsperf.com/comparison-to-undefined/3
  30881. //- slower code:
  30882. //-
  30883. //- if ( t >= t1 || t1 === undefined ) {
  30884. forward_scan: if ( ! ( t < t1 ) ) {
  30885. for ( let giveUpAt = i1 + 2; ; ) {
  30886. if ( t1 === undefined ) {
  30887. if ( t < t0 ) break forward_scan;
  30888. // after end
  30889. i1 = pp.length;
  30890. this._cachedIndex = i1;
  30891. return this.copySampleValue_( i1 - 1 );
  30892. }
  30893. if ( i1 === giveUpAt ) break; // this loop
  30894. t0 = t1;
  30895. t1 = pp[ ++ i1 ];
  30896. if ( t < t1 ) {
  30897. // we have arrived at the sought interval
  30898. break seek;
  30899. }
  30900. }
  30901. // prepare binary search on the right side of the index
  30902. right = pp.length;
  30903. break linear_scan;
  30904. }
  30905. //- slower code:
  30906. //- if ( t < t0 || t0 === undefined ) {
  30907. if ( ! ( t >= t0 ) ) {
  30908. // looping?
  30909. const t1global = pp[ 1 ];
  30910. if ( t < t1global ) {
  30911. i1 = 2; // + 1, using the scan for the details
  30912. t0 = t1global;
  30913. }
  30914. // linear reverse scan
  30915. for ( let giveUpAt = i1 - 2; ; ) {
  30916. if ( t0 === undefined ) {
  30917. // before start
  30918. this._cachedIndex = 0;
  30919. return this.copySampleValue_( 0 );
  30920. }
  30921. if ( i1 === giveUpAt ) break; // this loop
  30922. t1 = t0;
  30923. t0 = pp[ -- i1 - 1 ];
  30924. if ( t >= t0 ) {
  30925. // we have arrived at the sought interval
  30926. break seek;
  30927. }
  30928. }
  30929. // prepare binary search on the left side of the index
  30930. right = i1;
  30931. i1 = 0;
  30932. break linear_scan;
  30933. }
  30934. // the interval is valid
  30935. break validate_interval;
  30936. } // linear scan
  30937. // binary search
  30938. while ( i1 < right ) {
  30939. const mid = ( i1 + right ) >>> 1;
  30940. if ( t < pp[ mid ] ) {
  30941. right = mid;
  30942. } else {
  30943. i1 = mid + 1;
  30944. }
  30945. }
  30946. t1 = pp[ i1 ];
  30947. t0 = pp[ i1 - 1 ];
  30948. // check boundary cases, again
  30949. if ( t0 === undefined ) {
  30950. this._cachedIndex = 0;
  30951. return this.copySampleValue_( 0 );
  30952. }
  30953. if ( t1 === undefined ) {
  30954. i1 = pp.length;
  30955. this._cachedIndex = i1;
  30956. return this.copySampleValue_( i1 - 1 );
  30957. }
  30958. } // seek
  30959. this._cachedIndex = i1;
  30960. this.intervalChanged_( i1, t0, t1 );
  30961. } // validate_interval
  30962. return this.interpolate_( i1, t0, t, t1 );
  30963. }
  30964. /**
  30965. * Returns the interpolation settings.
  30966. *
  30967. * @return {Object} The interpolation settings.
  30968. */
  30969. getSettings_() {
  30970. return this.settings || this.DefaultSettings_;
  30971. }
  30972. /**
  30973. * Copies a sample value to the result buffer.
  30974. *
  30975. * @param {number} index - An index into the sample value buffer.
  30976. * @return {TypedArray} The result buffer.
  30977. */
  30978. copySampleValue_( index ) {
  30979. // copies a sample value to the result buffer
  30980. const result = this.resultBuffer,
  30981. values = this.sampleValues,
  30982. stride = this.valueSize,
  30983. offset = index * stride;
  30984. for ( let i = 0; i !== stride; ++ i ) {
  30985. result[ i ] = values[ offset + i ];
  30986. }
  30987. return result;
  30988. }
  30989. /**
  30990. * Copies a sample value to the result buffer.
  30991. *
  30992. * @abstract
  30993. * @param {number} i1 - An index into the sample value buffer.
  30994. * @param {number} t0 - The previous interpolation factor.
  30995. * @param {number} t - The current interpolation factor.
  30996. * @param {number} t1 - The next interpolation factor.
  30997. * @return {TypedArray} The result buffer.
  30998. */
  30999. interpolate_( /* i1, t0, t, t1 */ ) {
  31000. throw new Error( 'call to abstract method' );
  31001. // implementations shall return this.resultBuffer
  31002. }
  31003. /**
  31004. * Optional method that is executed when the interval has changed.
  31005. *
  31006. * @param {number} i1 - An index into the sample value buffer.
  31007. * @param {number} t0 - The previous interpolation factor.
  31008. * @param {number} t - The current interpolation factor.
  31009. */
  31010. intervalChanged_( /* i1, t0, t1 */ ) {
  31011. // empty
  31012. }
  31013. }
  31014. /**
  31015. * Fast and simple cubic spline interpolant.
  31016. *
  31017. * It was derived from a Hermitian construction setting the first derivative
  31018. * at each sample position to the linear slope between neighboring positions
  31019. * over their parameter interval.
  31020. *
  31021. * @augments Interpolant
  31022. */
  31023. class CubicInterpolant extends Interpolant {
  31024. /**
  31025. * Constructs a new cubic interpolant.
  31026. *
  31027. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31028. * @param {TypedArray} sampleValues - The sample values.
  31029. * @param {number} sampleSize - The sample size
  31030. * @param {TypedArray} [resultBuffer] - The result buffer.
  31031. */
  31032. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31033. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31034. this._weightPrev = -0;
  31035. this._offsetPrev = -0;
  31036. this._weightNext = -0;
  31037. this._offsetNext = -0;
  31038. this.DefaultSettings_ = {
  31039. endingStart: ZeroCurvatureEnding,
  31040. endingEnd: ZeroCurvatureEnding
  31041. };
  31042. }
  31043. intervalChanged_( i1, t0, t1 ) {
  31044. const pp = this.parameterPositions;
  31045. let iPrev = i1 - 2,
  31046. iNext = i1 + 1,
  31047. tPrev = pp[ iPrev ],
  31048. tNext = pp[ iNext ];
  31049. if ( tPrev === undefined ) {
  31050. switch ( this.getSettings_().endingStart ) {
  31051. case ZeroSlopeEnding:
  31052. // f'(t0) = 0
  31053. iPrev = i1;
  31054. tPrev = 2 * t0 - t1;
  31055. break;
  31056. case WrapAroundEnding:
  31057. // use the other end of the curve
  31058. iPrev = pp.length - 2;
  31059. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31060. break;
  31061. default: // ZeroCurvatureEnding
  31062. // f''(t0) = 0 a.k.a. Natural Spline
  31063. iPrev = i1;
  31064. tPrev = t1;
  31065. }
  31066. }
  31067. if ( tNext === undefined ) {
  31068. switch ( this.getSettings_().endingEnd ) {
  31069. case ZeroSlopeEnding:
  31070. // f'(tN) = 0
  31071. iNext = i1;
  31072. tNext = 2 * t1 - t0;
  31073. break;
  31074. case WrapAroundEnding:
  31075. // use the other end of the curve
  31076. iNext = 1;
  31077. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31078. break;
  31079. default: // ZeroCurvatureEnding
  31080. // f''(tN) = 0, a.k.a. Natural Spline
  31081. iNext = i1 - 1;
  31082. tNext = t0;
  31083. }
  31084. }
  31085. const halfDt = ( t1 - t0 ) * 0.5,
  31086. stride = this.valueSize;
  31087. this._weightPrev = halfDt / ( t0 - tPrev );
  31088. this._weightNext = halfDt / ( tNext - t1 );
  31089. this._offsetPrev = iPrev * stride;
  31090. this._offsetNext = iNext * stride;
  31091. }
  31092. interpolate_( i1, t0, t, t1 ) {
  31093. const result = this.resultBuffer,
  31094. values = this.sampleValues,
  31095. stride = this.valueSize,
  31096. o1 = i1 * stride, o0 = o1 - stride,
  31097. oP = this._offsetPrev, oN = this._offsetNext,
  31098. wP = this._weightPrev, wN = this._weightNext,
  31099. p = ( t - t0 ) / ( t1 - t0 ),
  31100. pp = p * p,
  31101. ppp = pp * p;
  31102. // evaluate polynomials
  31103. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31104. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31105. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31106. const sN = wN * ppp - wN * pp;
  31107. // combine data linearly
  31108. for ( let i = 0; i !== stride; ++ i ) {
  31109. result[ i ] =
  31110. sP * values[ oP + i ] +
  31111. s0 * values[ o0 + i ] +
  31112. s1 * values[ o1 + i ] +
  31113. sN * values[ oN + i ];
  31114. }
  31115. return result;
  31116. }
  31117. }
  31118. /**
  31119. * A basic linear interpolant.
  31120. *
  31121. * @augments Interpolant
  31122. */
  31123. class LinearInterpolant extends Interpolant {
  31124. /**
  31125. * Constructs a new linear interpolant.
  31126. *
  31127. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31128. * @param {TypedArray} sampleValues - The sample values.
  31129. * @param {number} sampleSize - The sample size
  31130. * @param {TypedArray} [resultBuffer] - The result buffer.
  31131. */
  31132. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31133. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31134. }
  31135. interpolate_( i1, t0, t, t1 ) {
  31136. const result = this.resultBuffer,
  31137. values = this.sampleValues,
  31138. stride = this.valueSize,
  31139. offset1 = i1 * stride,
  31140. offset0 = offset1 - stride,
  31141. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31142. weight0 = 1 - weight1;
  31143. for ( let i = 0; i !== stride; ++ i ) {
  31144. result[ i ] =
  31145. values[ offset0 + i ] * weight0 +
  31146. values[ offset1 + i ] * weight1;
  31147. }
  31148. return result;
  31149. }
  31150. }
  31151. /**
  31152. * Interpolant that evaluates to the sample value at the position preceding
  31153. * the parameter.
  31154. *
  31155. * @augments Interpolant
  31156. */
  31157. class DiscreteInterpolant extends Interpolant {
  31158. /**
  31159. * Constructs a new discrete interpolant.
  31160. *
  31161. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31162. * @param {TypedArray} sampleValues - The sample values.
  31163. * @param {number} sampleSize - The sample size
  31164. * @param {TypedArray} [resultBuffer] - The result buffer.
  31165. */
  31166. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31167. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31168. }
  31169. interpolate_( i1 /*, t0, t, t1 */ ) {
  31170. return this.copySampleValue_( i1 - 1 );
  31171. }
  31172. }
  31173. /**
  31174. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  31175. *
  31176. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  31177. * each keyframe has explicit in/out tangent control points specified as
  31178. * 2D coordinates (time, value).
  31179. *
  31180. * The tangent data must be provided via the `settings` object:
  31181. * - `settings.inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31182. * - `settings.outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31183. *
  31184. * For a track with N keyframes and stride S:
  31185. * - Each tangent array has N * S * 2 values
  31186. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  31187. * k1_c0_time, k1_c0_value, ...]
  31188. *
  31189. * @augments Interpolant
  31190. */
  31191. class BezierInterpolant extends Interpolant {
  31192. interpolate_( i1, t0, t, t1 ) {
  31193. const result = this.resultBuffer;
  31194. const values = this.sampleValues;
  31195. const stride = this.valueSize;
  31196. const offset1 = i1 * stride;
  31197. const offset0 = offset1 - stride;
  31198. const settings = this.settings || this.DefaultSettings_;
  31199. const inTangents = settings.inTangents;
  31200. const outTangents = settings.outTangents;
  31201. // If no tangent data, fall back to linear interpolation
  31202. if ( ! inTangents || ! outTangents ) {
  31203. const weight1 = ( t - t0 ) / ( t1 - t0 );
  31204. const weight0 = 1 - weight1;
  31205. for ( let i = 0; i !== stride; ++ i ) {
  31206. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  31207. }
  31208. return result;
  31209. }
  31210. const tangentStride = stride * 2;
  31211. const i0 = i1 - 1;
  31212. for ( let i = 0; i !== stride; ++ i ) {
  31213. const v0 = values[ offset0 + i ];
  31214. const v1 = values[ offset1 + i ];
  31215. // outTangent of previous keyframe (C0)
  31216. const outTangentOffset = i0 * tangentStride + i * 2;
  31217. const c0x = outTangents[ outTangentOffset ];
  31218. const c0y = outTangents[ outTangentOffset + 1 ];
  31219. // inTangent of current keyframe (C1)
  31220. const inTangentOffset = i1 * tangentStride + i * 2;
  31221. const c1x = inTangents[ inTangentOffset ];
  31222. const c1y = inTangents[ inTangentOffset + 1 ];
  31223. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  31224. let s = ( t - t0 ) / ( t1 - t0 );
  31225. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  31226. for ( let iter = 0; iter < 8; iter ++ ) {
  31227. s2 = s * s;
  31228. s3 = s2 * s;
  31229. oneMinusS = 1 - s;
  31230. oneMinusS2 = oneMinusS * oneMinusS;
  31231. oneMinusS3 = oneMinusS2 * oneMinusS;
  31232. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  31233. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  31234. const error = bx - t;
  31235. if ( Math.abs( error ) < 1e-10 ) break;
  31236. // Derivative dX/ds
  31237. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  31238. if ( Math.abs( dbx ) < 1e-10 ) break;
  31239. s = s - error / dbx;
  31240. s = Math.max( 0, Math.min( 1, s ) );
  31241. }
  31242. // Evaluate Bezier Y(s)
  31243. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  31244. }
  31245. return result;
  31246. }
  31247. }
  31248. /**
  31249. * Represents a timed sequence of keyframes, which are composed of lists of
  31250. * times and related values, and which are used to animate a specific property
  31251. * of an object.
  31252. */
  31253. class KeyframeTrack {
  31254. /**
  31255. * Constructs a new keyframe track.
  31256. *
  31257. * @param {string} name - The keyframe track's name.
  31258. * @param {Array<number>} times - A list of keyframe times.
  31259. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31260. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  31261. */
  31262. constructor( name, times, values, interpolation ) {
  31263. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31264. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31265. /**
  31266. * The track's name can refer to morph targets or bones or
  31267. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31268. * for the forms of strings that can be parsed for property binding.
  31269. *
  31270. * @type {string}
  31271. */
  31272. this.name = name;
  31273. /**
  31274. * The keyframe times.
  31275. *
  31276. * @type {Float32Array}
  31277. */
  31278. this.times = convertArray( times, this.TimeBufferType );
  31279. /**
  31280. * The keyframe values.
  31281. *
  31282. * @type {Float32Array}
  31283. */
  31284. this.values = convertArray( values, this.ValueBufferType );
  31285. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31286. }
  31287. /**
  31288. * Converts the keyframe track to JSON.
  31289. *
  31290. * @static
  31291. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31292. * @return {Object} The serialized keyframe track as JSON.
  31293. */
  31294. static toJSON( track ) {
  31295. const trackType = track.constructor;
  31296. let json;
  31297. // derived classes can define a static toJSON method
  31298. if ( trackType.toJSON !== this.toJSON ) {
  31299. json = trackType.toJSON( track );
  31300. } else {
  31301. // by default, we assume the data can be serialized as-is
  31302. json = {
  31303. 'name': track.name,
  31304. 'times': convertArray( track.times, Array ),
  31305. 'values': convertArray( track.values, Array )
  31306. };
  31307. const interpolation = track.getInterpolation();
  31308. if ( interpolation !== track.DefaultInterpolation ) {
  31309. json.interpolation = interpolation;
  31310. }
  31311. }
  31312. json.type = track.ValueTypeName; // mandatory
  31313. return json;
  31314. }
  31315. /**
  31316. * Factory method for creating a new discrete interpolant.
  31317. *
  31318. * @static
  31319. * @param {TypedArray} [result] - The result buffer.
  31320. * @return {DiscreteInterpolant} The new interpolant.
  31321. */
  31322. InterpolantFactoryMethodDiscrete( result ) {
  31323. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31324. }
  31325. /**
  31326. * Factory method for creating a new linear interpolant.
  31327. *
  31328. * @static
  31329. * @param {TypedArray} [result] - The result buffer.
  31330. * @return {LinearInterpolant} The new interpolant.
  31331. */
  31332. InterpolantFactoryMethodLinear( result ) {
  31333. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31334. }
  31335. /**
  31336. * Factory method for creating a new smooth interpolant.
  31337. *
  31338. * @static
  31339. * @param {TypedArray} [result] - The result buffer.
  31340. * @return {CubicInterpolant} The new interpolant.
  31341. */
  31342. InterpolantFactoryMethodSmooth( result ) {
  31343. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31344. }
  31345. /**
  31346. * Factory method for creating a new Bezier interpolant.
  31347. *
  31348. * The Bezier interpolant requires tangent data to be set via the `settings` property
  31349. * on the track before creating the interpolant. The settings should contain:
  31350. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31351. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31352. *
  31353. * @static
  31354. * @param {TypedArray} [result] - The result buffer.
  31355. * @return {BezierInterpolant} The new interpolant.
  31356. */
  31357. InterpolantFactoryMethodBezier( result ) {
  31358. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  31359. // Pass tangent data from track settings to interpolant
  31360. if ( this.settings ) {
  31361. interpolant.settings = this.settings;
  31362. }
  31363. return interpolant;
  31364. }
  31365. /**
  31366. * Defines the interpolation factor method for this keyframe track.
  31367. *
  31368. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  31369. * @return {KeyframeTrack} A reference to this keyframe track.
  31370. */
  31371. setInterpolation( interpolation ) {
  31372. let factoryMethod;
  31373. switch ( interpolation ) {
  31374. case InterpolateDiscrete:
  31375. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31376. break;
  31377. case InterpolateLinear:
  31378. factoryMethod = this.InterpolantFactoryMethodLinear;
  31379. break;
  31380. case InterpolateSmooth:
  31381. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31382. break;
  31383. case InterpolateBezier:
  31384. factoryMethod = this.InterpolantFactoryMethodBezier;
  31385. break;
  31386. }
  31387. if ( factoryMethod === undefined ) {
  31388. const message = 'unsupported interpolation for ' +
  31389. this.ValueTypeName + ' keyframe track named ' + this.name;
  31390. if ( this.createInterpolant === undefined ) {
  31391. // fall back to default, unless the default itself is messed up
  31392. if ( interpolation !== this.DefaultInterpolation ) {
  31393. this.setInterpolation( this.DefaultInterpolation );
  31394. } else {
  31395. throw new Error( message ); // fatal, in this case
  31396. }
  31397. }
  31398. warn( 'KeyframeTrack:', message );
  31399. return this;
  31400. }
  31401. this.createInterpolant = factoryMethod;
  31402. return this;
  31403. }
  31404. /**
  31405. * Returns the current interpolation type.
  31406. *
  31407. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  31408. */
  31409. getInterpolation() {
  31410. switch ( this.createInterpolant ) {
  31411. case this.InterpolantFactoryMethodDiscrete:
  31412. return InterpolateDiscrete;
  31413. case this.InterpolantFactoryMethodLinear:
  31414. return InterpolateLinear;
  31415. case this.InterpolantFactoryMethodSmooth:
  31416. return InterpolateSmooth;
  31417. case this.InterpolantFactoryMethodBezier:
  31418. return InterpolateBezier;
  31419. }
  31420. }
  31421. /**
  31422. * Returns the value size.
  31423. *
  31424. * @return {number} The value size.
  31425. */
  31426. getValueSize() {
  31427. return this.values.length / this.times.length;
  31428. }
  31429. /**
  31430. * Moves all keyframes either forward or backward in time.
  31431. *
  31432. * @param {number} timeOffset - The offset to move the time values.
  31433. * @return {KeyframeTrack} A reference to this keyframe track.
  31434. */
  31435. shift( timeOffset ) {
  31436. if ( timeOffset !== 0.0 ) {
  31437. const times = this.times;
  31438. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31439. times[ i ] += timeOffset;
  31440. }
  31441. }
  31442. return this;
  31443. }
  31444. /**
  31445. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31446. *
  31447. * @param {number} timeScale - The time scale.
  31448. * @return {KeyframeTrack} A reference to this keyframe track.
  31449. */
  31450. scale( timeScale ) {
  31451. if ( timeScale !== 1.0 ) {
  31452. const times = this.times;
  31453. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31454. times[ i ] *= timeScale;
  31455. }
  31456. }
  31457. return this;
  31458. }
  31459. /**
  31460. * Removes keyframes before and after animation without changing any values within the defined time range.
  31461. *
  31462. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31463. * keys this will change their values
  31464. *
  31465. * @param {number} startTime - The start time.
  31466. * @param {number} endTime - The end time.
  31467. * @return {KeyframeTrack} A reference to this keyframe track.
  31468. */
  31469. trim( startTime, endTime ) {
  31470. const times = this.times,
  31471. nKeys = times.length;
  31472. let from = 0,
  31473. to = nKeys - 1;
  31474. while ( from !== nKeys && times[ from ] < startTime ) {
  31475. ++ from;
  31476. }
  31477. while ( to !== -1 && times[ to ] > endTime ) {
  31478. -- to;
  31479. }
  31480. ++ to; // inclusive -> exclusive bound
  31481. if ( from !== 0 || to !== nKeys ) {
  31482. // empty tracks are forbidden, so keep at least one keyframe
  31483. if ( from >= to ) {
  31484. to = Math.max( to, 1 );
  31485. from = to - 1;
  31486. }
  31487. const stride = this.getValueSize();
  31488. this.times = times.slice( from, to );
  31489. this.values = this.values.slice( from * stride, to * stride );
  31490. }
  31491. return this;
  31492. }
  31493. /**
  31494. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31495. * are valid.
  31496. *
  31497. * @return {boolean} Whether the keyframes are valid or not.
  31498. */
  31499. validate() {
  31500. let valid = true;
  31501. const valueSize = this.getValueSize();
  31502. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31503. error( 'KeyframeTrack: Invalid value size in track.', this );
  31504. valid = false;
  31505. }
  31506. const times = this.times,
  31507. values = this.values,
  31508. nKeys = times.length;
  31509. if ( nKeys === 0 ) {
  31510. error( 'KeyframeTrack: Track is empty.', this );
  31511. valid = false;
  31512. }
  31513. let prevTime = null;
  31514. for ( let i = 0; i !== nKeys; i ++ ) {
  31515. const currTime = times[ i ];
  31516. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31517. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31518. valid = false;
  31519. break;
  31520. }
  31521. if ( prevTime !== null && prevTime > currTime ) {
  31522. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31523. valid = false;
  31524. break;
  31525. }
  31526. prevTime = currTime;
  31527. }
  31528. if ( values !== undefined ) {
  31529. if ( isTypedArray( values ) ) {
  31530. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31531. const value = values[ i ];
  31532. if ( isNaN( value ) ) {
  31533. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31534. valid = false;
  31535. break;
  31536. }
  31537. }
  31538. }
  31539. }
  31540. return valid;
  31541. }
  31542. /**
  31543. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31544. * common in morph target sequences).
  31545. *
  31546. * @return {KeyframeTrack} A reference to this keyframe track.
  31547. */
  31548. optimize() {
  31549. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31550. // times or values may be shared with other tracks, so overwriting is unsafe
  31551. const times = this.times.slice(),
  31552. values = this.values.slice(),
  31553. stride = this.getValueSize(),
  31554. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31555. lastIndex = times.length - 1;
  31556. let writeIndex = 1;
  31557. for ( let i = 1; i < lastIndex; ++ i ) {
  31558. let keep = false;
  31559. const time = times[ i ];
  31560. const timeNext = times[ i + 1 ];
  31561. // remove adjacent keyframes scheduled at the same time
  31562. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31563. if ( ! smoothInterpolation ) {
  31564. // remove unnecessary keyframes same as their neighbors
  31565. const offset = i * stride,
  31566. offsetP = offset - stride,
  31567. offsetN = offset + stride;
  31568. for ( let j = 0; j !== stride; ++ j ) {
  31569. const value = values[ offset + j ];
  31570. if ( value !== values[ offsetP + j ] ||
  31571. value !== values[ offsetN + j ] ) {
  31572. keep = true;
  31573. break;
  31574. }
  31575. }
  31576. } else {
  31577. keep = true;
  31578. }
  31579. }
  31580. // in-place compaction
  31581. if ( keep ) {
  31582. if ( i !== writeIndex ) {
  31583. times[ writeIndex ] = times[ i ];
  31584. const readOffset = i * stride,
  31585. writeOffset = writeIndex * stride;
  31586. for ( let j = 0; j !== stride; ++ j ) {
  31587. values[ writeOffset + j ] = values[ readOffset + j ];
  31588. }
  31589. }
  31590. ++ writeIndex;
  31591. }
  31592. }
  31593. // flush last keyframe (compaction looks ahead)
  31594. if ( lastIndex > 0 ) {
  31595. times[ writeIndex ] = times[ lastIndex ];
  31596. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31597. values[ writeOffset + j ] = values[ readOffset + j ];
  31598. }
  31599. ++ writeIndex;
  31600. }
  31601. if ( writeIndex !== times.length ) {
  31602. this.times = times.slice( 0, writeIndex );
  31603. this.values = values.slice( 0, writeIndex * stride );
  31604. } else {
  31605. this.times = times;
  31606. this.values = values;
  31607. }
  31608. return this;
  31609. }
  31610. /**
  31611. * Returns a new keyframe track with copied values from this instance.
  31612. *
  31613. * @return {KeyframeTrack} A clone of this instance.
  31614. */
  31615. clone() {
  31616. const times = this.times.slice();
  31617. const values = this.values.slice();
  31618. const TypedKeyframeTrack = this.constructor;
  31619. const track = new TypedKeyframeTrack( this.name, times, values );
  31620. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31621. track.createInterpolant = this.createInterpolant;
  31622. return track;
  31623. }
  31624. }
  31625. /**
  31626. * The value type name.
  31627. *
  31628. * @type {string}
  31629. * @default ''
  31630. */
  31631. KeyframeTrack.prototype.ValueTypeName = '';
  31632. /**
  31633. * The time buffer type of this keyframe track.
  31634. *
  31635. * @type {TypedArray|Array}
  31636. * @default Float32Array.constructor
  31637. */
  31638. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31639. /**
  31640. * The value buffer type of this keyframe track.
  31641. *
  31642. * @type {TypedArray|Array}
  31643. * @default Float32Array.constructor
  31644. */
  31645. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31646. /**
  31647. * The default interpolation type of this keyframe track.
  31648. *
  31649. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31650. * @default InterpolateLinear
  31651. */
  31652. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31653. /**
  31654. * A track for boolean keyframe values.
  31655. *
  31656. * @augments KeyframeTrack
  31657. */
  31658. class BooleanKeyframeTrack extends KeyframeTrack {
  31659. /**
  31660. * Constructs a new boolean keyframe track.
  31661. *
  31662. * This keyframe track type has no `interpolation` parameter because the
  31663. * interpolation is always discrete.
  31664. *
  31665. * @param {string} name - The keyframe track's name.
  31666. * @param {Array<number>} times - A list of keyframe times.
  31667. * @param {Array<boolean>} values - A list of keyframe values.
  31668. */
  31669. constructor( name, times, values ) {
  31670. super( name, times, values );
  31671. }
  31672. }
  31673. /**
  31674. * The value type name.
  31675. *
  31676. * @type {string}
  31677. * @default 'bool'
  31678. */
  31679. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31680. /**
  31681. * The value buffer type of this keyframe track.
  31682. *
  31683. * @type {TypedArray|Array}
  31684. * @default Array.constructor
  31685. */
  31686. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31687. /**
  31688. * The default interpolation type of this keyframe track.
  31689. *
  31690. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31691. * @default InterpolateDiscrete
  31692. */
  31693. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31694. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31695. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31696. /**
  31697. * A track for color keyframe values.
  31698. *
  31699. * @augments KeyframeTrack
  31700. */
  31701. class ColorKeyframeTrack extends KeyframeTrack {
  31702. /**
  31703. * Constructs a new color keyframe track.
  31704. *
  31705. * @param {string} name - The keyframe track's name.
  31706. * @param {Array<number>} times - A list of keyframe times.
  31707. * @param {Array<number>} values - A list of keyframe values.
  31708. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31709. */
  31710. constructor( name, times, values, interpolation ) {
  31711. super( name, times, values, interpolation );
  31712. }
  31713. }
  31714. /**
  31715. * The value type name.
  31716. *
  31717. * @type {string}
  31718. * @default 'color'
  31719. */
  31720. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31721. /**
  31722. * A track for numeric keyframe values.
  31723. *
  31724. * @augments KeyframeTrack
  31725. */
  31726. class NumberKeyframeTrack extends KeyframeTrack {
  31727. /**
  31728. * Constructs a new number keyframe track.
  31729. *
  31730. * @param {string} name - The keyframe track's name.
  31731. * @param {Array<number>} times - A list of keyframe times.
  31732. * @param {Array<number>} values - A list of keyframe values.
  31733. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31734. */
  31735. constructor( name, times, values, interpolation ) {
  31736. super( name, times, values, interpolation );
  31737. }
  31738. }
  31739. /**
  31740. * The value type name.
  31741. *
  31742. * @type {string}
  31743. * @default 'number'
  31744. */
  31745. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31746. /**
  31747. * Spherical linear unit quaternion interpolant.
  31748. *
  31749. * @augments Interpolant
  31750. */
  31751. class QuaternionLinearInterpolant extends Interpolant {
  31752. /**
  31753. * Constructs a new SLERP interpolant.
  31754. *
  31755. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31756. * @param {TypedArray} sampleValues - The sample values.
  31757. * @param {number} sampleSize - The sample size
  31758. * @param {TypedArray} [resultBuffer] - The result buffer.
  31759. */
  31760. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31761. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31762. }
  31763. interpolate_( i1, t0, t, t1 ) {
  31764. const result = this.resultBuffer,
  31765. values = this.sampleValues,
  31766. stride = this.valueSize,
  31767. alpha = ( t - t0 ) / ( t1 - t0 );
  31768. let offset = i1 * stride;
  31769. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31770. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31771. }
  31772. return result;
  31773. }
  31774. }
  31775. /**
  31776. * A track for Quaternion keyframe values.
  31777. *
  31778. * @augments KeyframeTrack
  31779. */
  31780. class QuaternionKeyframeTrack extends KeyframeTrack {
  31781. /**
  31782. * Constructs a new Quaternion keyframe track.
  31783. *
  31784. * @param {string} name - The keyframe track's name.
  31785. * @param {Array<number>} times - A list of keyframe times.
  31786. * @param {Array<number>} values - A list of keyframe values.
  31787. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31788. */
  31789. constructor( name, times, values, interpolation ) {
  31790. super( name, times, values, interpolation );
  31791. }
  31792. /**
  31793. * Overwritten so the method returns Quaternion based interpolant.
  31794. *
  31795. * @static
  31796. * @param {TypedArray} [result] - The result buffer.
  31797. * @return {QuaternionLinearInterpolant} The new interpolant.
  31798. */
  31799. InterpolantFactoryMethodLinear( result ) {
  31800. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31801. }
  31802. }
  31803. /**
  31804. * The value type name.
  31805. *
  31806. * @type {string}
  31807. * @default 'quaternion'
  31808. */
  31809. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31810. // ValueBufferType is inherited
  31811. // DefaultInterpolation is inherited;
  31812. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31813. /**
  31814. * A track for string keyframe values.
  31815. *
  31816. * @augments KeyframeTrack
  31817. */
  31818. class StringKeyframeTrack extends KeyframeTrack {
  31819. /**
  31820. * Constructs a new string keyframe track.
  31821. *
  31822. * This keyframe track type has no `interpolation` parameter because the
  31823. * interpolation is always discrete.
  31824. *
  31825. * @param {string} name - The keyframe track's name.
  31826. * @param {Array<number>} times - A list of keyframe times.
  31827. * @param {Array<string>} values - A list of keyframe values.
  31828. */
  31829. constructor( name, times, values ) {
  31830. super( name, times, values );
  31831. }
  31832. }
  31833. /**
  31834. * The value type name.
  31835. *
  31836. * @type {string}
  31837. * @default 'string'
  31838. */
  31839. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31840. /**
  31841. * The value buffer type of this keyframe track.
  31842. *
  31843. * @type {TypedArray|Array}
  31844. * @default Array.constructor
  31845. */
  31846. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31847. /**
  31848. * The default interpolation type of this keyframe track.
  31849. *
  31850. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31851. * @default InterpolateDiscrete
  31852. */
  31853. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31854. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31855. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31856. /**
  31857. * A track for vector keyframe values.
  31858. *
  31859. * @augments KeyframeTrack
  31860. */
  31861. class VectorKeyframeTrack extends KeyframeTrack {
  31862. /**
  31863. * Constructs a new vector keyframe track.
  31864. *
  31865. * @param {string} name - The keyframe track's name.
  31866. * @param {Array<number>} times - A list of keyframe times.
  31867. * @param {Array<number>} values - A list of keyframe values.
  31868. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31869. */
  31870. constructor( name, times, values, interpolation ) {
  31871. super( name, times, values, interpolation );
  31872. }
  31873. }
  31874. /**
  31875. * The value type name.
  31876. *
  31877. * @type {string}
  31878. * @default 'vector'
  31879. */
  31880. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31881. /**
  31882. * A reusable set of keyframe tracks which represent an animation.
  31883. */
  31884. class AnimationClip {
  31885. /**
  31886. * Constructs a new animation clip.
  31887. *
  31888. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31889. * use the static interface of this class for creating clips. In most cases though, animation clips
  31890. * will automatically be created by loaders when importing animated 3D assets.
  31891. *
  31892. * @param {string} [name=''] - The clip's name.
  31893. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31894. * the duration will be calculated from the passed keyframes.
  31895. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31896. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31897. * is blended/combined when two or more animations are simultaneously played.
  31898. */
  31899. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31900. /**
  31901. * The clip's name.
  31902. *
  31903. * @type {string}
  31904. */
  31905. this.name = name;
  31906. /**
  31907. * An array of keyframe tracks.
  31908. *
  31909. * @type {Array<KeyframeTrack>}
  31910. */
  31911. this.tracks = tracks;
  31912. /**
  31913. * The clip's duration in seconds.
  31914. *
  31915. * @type {number}
  31916. */
  31917. this.duration = duration;
  31918. /**
  31919. * Defines how the animation is blended/combined when two or more animations
  31920. * are simultaneously played.
  31921. *
  31922. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31923. */
  31924. this.blendMode = blendMode;
  31925. /**
  31926. * The UUID of the animation clip.
  31927. *
  31928. * @type {string}
  31929. * @readonly
  31930. */
  31931. this.uuid = generateUUID();
  31932. /**
  31933. * An object that can be used to store custom data about the animation clip.
  31934. * It should not hold references to functions as these will not be cloned.
  31935. *
  31936. * @type {Object}
  31937. */
  31938. this.userData = {};
  31939. // this means it should figure out its duration by scanning the tracks
  31940. if ( this.duration < 0 ) {
  31941. this.resetDuration();
  31942. }
  31943. }
  31944. /**
  31945. * Factory method for creating an animation clip from the given JSON.
  31946. *
  31947. * @static
  31948. * @param {Object} json - The serialized animation clip.
  31949. * @return {AnimationClip} The new animation clip.
  31950. */
  31951. static parse( json ) {
  31952. const tracks = [],
  31953. jsonTracks = json.tracks,
  31954. frameTime = 1.0 / ( json.fps || 1.0 );
  31955. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31956. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31957. }
  31958. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31959. clip.uuid = json.uuid;
  31960. clip.userData = JSON.parse( json.userData || '{}' );
  31961. return clip;
  31962. }
  31963. /**
  31964. * Serializes the given animation clip into JSON.
  31965. *
  31966. * @static
  31967. * @param {AnimationClip} clip - The animation clip to serialize.
  31968. * @return {Object} The JSON object.
  31969. */
  31970. static toJSON( clip ) {
  31971. const tracks = [],
  31972. clipTracks = clip.tracks;
  31973. const json = {
  31974. 'name': clip.name,
  31975. 'duration': clip.duration,
  31976. 'tracks': tracks,
  31977. 'uuid': clip.uuid,
  31978. 'blendMode': clip.blendMode,
  31979. 'userData': JSON.stringify( clip.userData ),
  31980. };
  31981. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31982. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31983. }
  31984. return json;
  31985. }
  31986. /**
  31987. * Returns a new animation clip from the passed morph targets array of a
  31988. * geometry, taking a name and the number of frames per second.
  31989. *
  31990. * Note: The fps parameter is required, but the animation speed can be
  31991. * overridden via {@link AnimationAction#setDuration}.
  31992. *
  31993. * @static
  31994. * @param {string} name - The name of the animation clip.
  31995. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31996. * @param {number} fps - The Frames-Per-Second value.
  31997. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31998. * @return {AnimationClip} The new animation clip.
  31999. */
  32000. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  32001. const numMorphTargets = morphTargetSequence.length;
  32002. const tracks = [];
  32003. for ( let i = 0; i < numMorphTargets; i ++ ) {
  32004. let times = [];
  32005. let values = [];
  32006. times.push(
  32007. ( i + numMorphTargets - 1 ) % numMorphTargets,
  32008. i,
  32009. ( i + 1 ) % numMorphTargets );
  32010. values.push( 0, 1, 0 );
  32011. const order = getKeyframeOrder( times );
  32012. times = sortedArray( times, 1, order );
  32013. values = sortedArray( values, 1, order );
  32014. // if there is a key at the first frame, duplicate it as the
  32015. // last frame as well for perfect loop.
  32016. if ( ! noLoop && times[ 0 ] === 0 ) {
  32017. times.push( numMorphTargets );
  32018. values.push( values[ 0 ] );
  32019. }
  32020. tracks.push(
  32021. new NumberKeyframeTrack(
  32022. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  32023. times, values
  32024. ).scale( 1.0 / fps ) );
  32025. }
  32026. return new this( name, -1, tracks );
  32027. }
  32028. /**
  32029. * Searches for an animation clip by name, taking as its first parameter
  32030. * either an array of clips, or a mesh or geometry that contains an
  32031. * array named "animations" property.
  32032. *
  32033. * @static
  32034. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  32035. * @param {string} name - The name to search for.
  32036. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  32037. */
  32038. static findByName( objectOrClipArray, name ) {
  32039. let clipArray = objectOrClipArray;
  32040. if ( ! Array.isArray( objectOrClipArray ) ) {
  32041. const o = objectOrClipArray;
  32042. clipArray = o.geometry && o.geometry.animations || o.animations;
  32043. }
  32044. for ( let i = 0; i < clipArray.length; i ++ ) {
  32045. if ( clipArray[ i ].name === name ) {
  32046. return clipArray[ i ];
  32047. }
  32048. }
  32049. return null;
  32050. }
  32051. /**
  32052. * Returns an array of new AnimationClips created from the morph target
  32053. * sequences of a geometry, trying to sort morph target names into
  32054. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  32055. *
  32056. * See {@link MD2Loader#parse} as an example for how the method should be used.
  32057. *
  32058. * @static
  32059. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  32060. * @param {number} fps - The Frames-Per-Second value.
  32061. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  32062. * @return {Array<AnimationClip>} An array of new animation clips.
  32063. */
  32064. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  32065. const animationToMorphTargets = {};
  32066. // tested with https://regex101.com/ on trick sequences
  32067. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  32068. const pattern = /^([\w-]*?)([\d]+)$/;
  32069. // sort morph target names into animation groups based
  32070. // patterns like Walk_001, Walk_002, Run_001, Run_002
  32071. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  32072. const morphTarget = morphTargets[ i ];
  32073. const parts = morphTarget.name.match( pattern );
  32074. if ( parts && parts.length > 1 ) {
  32075. const name = parts[ 1 ];
  32076. let animationMorphTargets = animationToMorphTargets[ name ];
  32077. if ( ! animationMorphTargets ) {
  32078. animationToMorphTargets[ name ] = animationMorphTargets = [];
  32079. }
  32080. animationMorphTargets.push( morphTarget );
  32081. }
  32082. }
  32083. const clips = [];
  32084. for ( const name in animationToMorphTargets ) {
  32085. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  32086. }
  32087. return clips;
  32088. }
  32089. /**
  32090. * Parses the `animation.hierarchy` format and returns a new animation clip.
  32091. *
  32092. * @static
  32093. * @deprecated since r175.
  32094. * @param {Object} animation - A serialized animation clip as JSON.
  32095. * @param {Array<Bone>} bones - An array of bones.
  32096. * @return {?AnimationClip} The new animation clip.
  32097. */
  32098. static parseAnimation( animation, bones ) {
  32099. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  32100. if ( ! animation ) {
  32101. error( 'AnimationClip: No animation in JSONLoader data.' );
  32102. return null;
  32103. }
  32104. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  32105. // only return track if there are actually keys.
  32106. if ( animationKeys.length !== 0 ) {
  32107. const times = [];
  32108. const values = [];
  32109. flattenJSON( animationKeys, times, values, propertyName );
  32110. // empty keys are filtered out, so check again
  32111. if ( times.length !== 0 ) {
  32112. destTracks.push( new trackType( trackName, times, values ) );
  32113. }
  32114. }
  32115. };
  32116. const tracks = [];
  32117. const clipName = animation.name || 'default';
  32118. const fps = animation.fps || 30;
  32119. const blendMode = animation.blendMode;
  32120. // automatic length determination in AnimationClip.
  32121. let duration = animation.length || -1;
  32122. const hierarchyTracks = animation.hierarchy || [];
  32123. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  32124. const animationKeys = hierarchyTracks[ h ].keys;
  32125. // skip empty tracks
  32126. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  32127. // process morph targets
  32128. if ( animationKeys[ 0 ].morphTargets ) {
  32129. // figure out all morph targets used in this track
  32130. const morphTargetNames = {};
  32131. let k;
  32132. for ( k = 0; k < animationKeys.length; k ++ ) {
  32133. if ( animationKeys[ k ].morphTargets ) {
  32134. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  32135. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  32136. }
  32137. }
  32138. }
  32139. // create a track for each morph target with all zero
  32140. // morphTargetInfluences except for the keys in which
  32141. // the morphTarget is named.
  32142. for ( const morphTargetName in morphTargetNames ) {
  32143. const times = [];
  32144. const values = [];
  32145. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  32146. const animationKey = animationKeys[ k ];
  32147. times.push( animationKey.time );
  32148. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  32149. }
  32150. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  32151. }
  32152. duration = morphTargetNames.length * fps;
  32153. } else {
  32154. // ...assume skeletal animation
  32155. const boneName = '.bones[' + bones[ h ].name + ']';
  32156. addNonemptyTrack(
  32157. VectorKeyframeTrack, boneName + '.position',
  32158. animationKeys, 'pos', tracks );
  32159. addNonemptyTrack(
  32160. QuaternionKeyframeTrack, boneName + '.quaternion',
  32161. animationKeys, 'rot', tracks );
  32162. addNonemptyTrack(
  32163. VectorKeyframeTrack, boneName + '.scale',
  32164. animationKeys, 'scl', tracks );
  32165. }
  32166. }
  32167. if ( tracks.length === 0 ) {
  32168. return null;
  32169. }
  32170. const clip = new this( clipName, duration, tracks, blendMode );
  32171. return clip;
  32172. }
  32173. /**
  32174. * Sets the duration of this clip to the duration of its longest keyframe track.
  32175. *
  32176. * @return {AnimationClip} A reference to this animation clip.
  32177. */
  32178. resetDuration() {
  32179. const tracks = this.tracks;
  32180. let duration = 0;
  32181. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32182. const track = this.tracks[ i ];
  32183. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32184. }
  32185. this.duration = duration;
  32186. return this;
  32187. }
  32188. /**
  32189. * Trims all tracks to the clip's duration.
  32190. *
  32191. * @return {AnimationClip} A reference to this animation clip.
  32192. */
  32193. trim() {
  32194. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32195. this.tracks[ i ].trim( 0, this.duration );
  32196. }
  32197. return this;
  32198. }
  32199. /**
  32200. * Performs minimal validation on each track in the clip. Returns `true` if all
  32201. * tracks are valid.
  32202. *
  32203. * @return {boolean} Whether the clip's keyframes are valid or not.
  32204. */
  32205. validate() {
  32206. let valid = true;
  32207. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32208. valid = valid && this.tracks[ i ].validate();
  32209. }
  32210. return valid;
  32211. }
  32212. /**
  32213. * Optimizes each track by removing equivalent sequential keys (which are
  32214. * common in morph target sequences).
  32215. *
  32216. * @return {AnimationClip} A reference to this animation clip.
  32217. */
  32218. optimize() {
  32219. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32220. this.tracks[ i ].optimize();
  32221. }
  32222. return this;
  32223. }
  32224. /**
  32225. * Returns a new animation clip with copied values from this instance.
  32226. *
  32227. * @return {AnimationClip} A clone of this instance.
  32228. */
  32229. clone() {
  32230. const tracks = [];
  32231. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32232. tracks.push( this.tracks[ i ].clone() );
  32233. }
  32234. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32235. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32236. return clip;
  32237. }
  32238. /**
  32239. * Serializes this animation clip into JSON.
  32240. *
  32241. * @return {Object} The JSON object.
  32242. */
  32243. toJSON() {
  32244. return this.constructor.toJSON( this );
  32245. }
  32246. }
  32247. function getTrackTypeForValueTypeName( typeName ) {
  32248. switch ( typeName.toLowerCase() ) {
  32249. case 'scalar':
  32250. case 'double':
  32251. case 'float':
  32252. case 'number':
  32253. case 'integer':
  32254. return NumberKeyframeTrack;
  32255. case 'vector':
  32256. case 'vector2':
  32257. case 'vector3':
  32258. case 'vector4':
  32259. return VectorKeyframeTrack;
  32260. case 'color':
  32261. return ColorKeyframeTrack;
  32262. case 'quaternion':
  32263. return QuaternionKeyframeTrack;
  32264. case 'bool':
  32265. case 'boolean':
  32266. return BooleanKeyframeTrack;
  32267. case 'string':
  32268. return StringKeyframeTrack;
  32269. }
  32270. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32271. }
  32272. function parseKeyframeTrack( json ) {
  32273. if ( json.type === undefined ) {
  32274. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32275. }
  32276. const trackType = getTrackTypeForValueTypeName( json.type );
  32277. if ( json.times === undefined ) {
  32278. const times = [], values = [];
  32279. flattenJSON( json.keys, times, values, 'value' );
  32280. json.times = times;
  32281. json.values = values;
  32282. }
  32283. // derived classes can define a static parse method
  32284. if ( trackType.parse !== undefined ) {
  32285. return trackType.parse( json );
  32286. } else {
  32287. // by default, we assume a constructor compatible with the base
  32288. return new trackType( json.name, json.times, json.values, json.interpolation );
  32289. }
  32290. }
  32291. /**
  32292. * @class
  32293. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32294. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32295. * @hideconstructor
  32296. */
  32297. const Cache = {
  32298. /**
  32299. * Whether caching is enabled or not.
  32300. *
  32301. * @static
  32302. * @type {boolean}
  32303. * @default false
  32304. */
  32305. enabled: false,
  32306. /**
  32307. * A dictionary that holds cached files.
  32308. *
  32309. * @static
  32310. * @type {Object<string,Object>}
  32311. */
  32312. files: {},
  32313. /**
  32314. * Adds a cache entry with a key to reference the file. If this key already
  32315. * holds a file, it is overwritten.
  32316. *
  32317. * @static
  32318. * @param {string} key - The key to reference the cached file.
  32319. * @param {Object} file - The file to be cached.
  32320. */
  32321. add: function ( key, file ) {
  32322. if ( this.enabled === false ) return;
  32323. // log( 'Cache', 'Adding key:', key );
  32324. this.files[ key ] = file;
  32325. },
  32326. /**
  32327. * Gets the cached value for the given key.
  32328. *
  32329. * @static
  32330. * @param {string} key - The key to reference the cached file.
  32331. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32332. */
  32333. get: function ( key ) {
  32334. if ( this.enabled === false ) return;
  32335. // log( 'Cache', 'Checking key:', key );
  32336. return this.files[ key ];
  32337. },
  32338. /**
  32339. * Removes the cached file associated with the given key.
  32340. *
  32341. * @static
  32342. * @param {string} key - The key to reference the cached file.
  32343. */
  32344. remove: function ( key ) {
  32345. delete this.files[ key ];
  32346. },
  32347. /**
  32348. * Remove all values from the cache.
  32349. *
  32350. * @static
  32351. */
  32352. clear: function () {
  32353. this.files = {};
  32354. }
  32355. };
  32356. /**
  32357. * Handles and keeps track of loaded and pending data. A default global
  32358. * instance of this class is created and used by loaders if not supplied
  32359. * manually.
  32360. *
  32361. * In general that should be sufficient, however there are times when it can
  32362. * be useful to have separate loaders - for example if you want to show
  32363. * separate loading bars for objects and textures.
  32364. *
  32365. * ```js
  32366. * const manager = new THREE.LoadingManager();
  32367. * manager.onLoad = () => console.log( 'Loading complete!' );
  32368. *
  32369. * const loader1 = new OBJLoader( manager );
  32370. * const loader2 = new ColladaLoader( manager );
  32371. * ```
  32372. */
  32373. class LoadingManager {
  32374. /**
  32375. * Constructs a new loading manager.
  32376. *
  32377. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32378. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32379. * @param {Function} [onError] - Executes when an error occurs.
  32380. */
  32381. constructor( onLoad, onProgress, onError ) {
  32382. const scope = this;
  32383. let isLoading = false;
  32384. let itemsLoaded = 0;
  32385. let itemsTotal = 0;
  32386. let urlModifier = undefined;
  32387. const handlers = [];
  32388. // Refer to #5689 for the reason why we don't set .onStart
  32389. // in the constructor
  32390. /**
  32391. * Executes when an item starts loading.
  32392. *
  32393. * @type {Function|undefined}
  32394. * @default undefined
  32395. */
  32396. this.onStart = undefined;
  32397. /**
  32398. * Executes when all items have been loaded.
  32399. *
  32400. * @type {Function|undefined}
  32401. * @default undefined
  32402. */
  32403. this.onLoad = onLoad;
  32404. /**
  32405. * Executes when single items have been loaded.
  32406. *
  32407. * @type {Function|undefined}
  32408. * @default undefined
  32409. */
  32410. this.onProgress = onProgress;
  32411. /**
  32412. * Executes when an error occurs.
  32413. *
  32414. * @type {Function|undefined}
  32415. * @default undefined
  32416. */
  32417. this.onError = onError;
  32418. /**
  32419. * Used for aborting ongoing requests in loaders using this manager.
  32420. *
  32421. * @private
  32422. * @type {AbortController | null}
  32423. */
  32424. this._abortController = null;
  32425. /**
  32426. * This should be called by any loader using the manager when the loader
  32427. * starts loading an item.
  32428. *
  32429. * @param {string} url - The URL to load.
  32430. */
  32431. this.itemStart = function ( url ) {
  32432. itemsTotal ++;
  32433. if ( isLoading === false ) {
  32434. if ( scope.onStart !== undefined ) {
  32435. scope.onStart( url, itemsLoaded, itemsTotal );
  32436. }
  32437. }
  32438. isLoading = true;
  32439. };
  32440. /**
  32441. * This should be called by any loader using the manager when the loader
  32442. * ended loading an item.
  32443. *
  32444. * @param {string} url - The URL of the loaded item.
  32445. */
  32446. this.itemEnd = function ( url ) {
  32447. itemsLoaded ++;
  32448. if ( scope.onProgress !== undefined ) {
  32449. scope.onProgress( url, itemsLoaded, itemsTotal );
  32450. }
  32451. if ( itemsLoaded === itemsTotal ) {
  32452. isLoading = false;
  32453. if ( scope.onLoad !== undefined ) {
  32454. scope.onLoad();
  32455. }
  32456. }
  32457. };
  32458. /**
  32459. * This should be called by any loader using the manager when the loader
  32460. * encounters an error when loading an item.
  32461. *
  32462. * @param {string} url - The URL of the item that produces an error.
  32463. */
  32464. this.itemError = function ( url ) {
  32465. if ( scope.onError !== undefined ) {
  32466. scope.onError( url );
  32467. }
  32468. };
  32469. /**
  32470. * Given a URL, uses the URL modifier callback (if any) and returns a
  32471. * resolved URL. If no URL modifier is set, returns the original URL.
  32472. *
  32473. * @param {string} url - The URL to load.
  32474. * @return {string} The resolved URL.
  32475. */
  32476. this.resolveURL = function ( url ) {
  32477. if ( urlModifier ) {
  32478. return urlModifier( url );
  32479. }
  32480. return url;
  32481. };
  32482. /**
  32483. * If provided, the callback will be passed each resource URL before a
  32484. * request is sent. The callback may return the original URL, or a new URL to
  32485. * override loading behavior. This behavior can be used to load assets from
  32486. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32487. *
  32488. * ```js
  32489. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32490. *
  32491. * const manager = new THREE.LoadingManager();
  32492. *
  32493. * // Initialize loading manager with URL callback.
  32494. * const objectURLs = [];
  32495. * manager.setURLModifier( ( url ) => {
  32496. *
  32497. * url = URL.createObjectURL( blobs[ url ] );
  32498. * objectURLs.push( url );
  32499. * return url;
  32500. *
  32501. * } );
  32502. *
  32503. * // Load as usual, then revoke the blob URLs.
  32504. * const loader = new GLTFLoader( manager );
  32505. * loader.load( 'fish.gltf', (gltf) => {
  32506. *
  32507. * scene.add( gltf.scene );
  32508. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32509. *
  32510. * } );
  32511. * ```
  32512. *
  32513. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32514. * @return {LoadingManager} A reference to this loading manager.
  32515. */
  32516. this.setURLModifier = function ( transform ) {
  32517. urlModifier = transform;
  32518. return this;
  32519. };
  32520. /**
  32521. * Registers a loader with the given regular expression. Can be used to
  32522. * define what loader should be used in order to load specific files. A
  32523. * typical use case is to overwrite the default loader for textures.
  32524. *
  32525. * ```js
  32526. * // add handler for TGA textures
  32527. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32528. * ```
  32529. *
  32530. * @param {string} regex - A regular expression.
  32531. * @param {Loader} loader - A loader that should handle matched cases.
  32532. * @return {LoadingManager} A reference to this loading manager.
  32533. */
  32534. this.addHandler = function ( regex, loader ) {
  32535. handlers.push( regex, loader );
  32536. return this;
  32537. };
  32538. /**
  32539. * Removes the loader for the given regular expression.
  32540. *
  32541. * @param {string} regex - A regular expression.
  32542. * @return {LoadingManager} A reference to this loading manager.
  32543. */
  32544. this.removeHandler = function ( regex ) {
  32545. const index = handlers.indexOf( regex );
  32546. if ( index !== -1 ) {
  32547. handlers.splice( index, 2 );
  32548. }
  32549. return this;
  32550. };
  32551. /**
  32552. * Can be used to retrieve the registered loader for the given file path.
  32553. *
  32554. * @param {string} file - The file path.
  32555. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32556. */
  32557. this.getHandler = function ( file ) {
  32558. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32559. const regex = handlers[ i ];
  32560. const loader = handlers[ i + 1 ];
  32561. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32562. if ( regex.test( file ) ) {
  32563. return loader;
  32564. }
  32565. }
  32566. return null;
  32567. };
  32568. /**
  32569. * Can be used to abort ongoing loading requests in loaders using this manager.
  32570. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32571. * is supported in the browser.
  32572. *
  32573. * @return {LoadingManager} A reference to this loading manager.
  32574. */
  32575. this.abort = function () {
  32576. this.abortController.abort();
  32577. this._abortController = null;
  32578. return this;
  32579. };
  32580. }
  32581. // TODO: Revert this back to a single member variable once this issue has been fixed
  32582. // https://github.com/cloudflare/workerd/issues/3657
  32583. /**
  32584. * Used for aborting ongoing requests in loaders using this manager.
  32585. *
  32586. * @type {AbortController}
  32587. */
  32588. get abortController() {
  32589. if ( ! this._abortController ) {
  32590. this._abortController = new AbortController();
  32591. }
  32592. return this._abortController;
  32593. }
  32594. }
  32595. /**
  32596. * The global default loading manager.
  32597. *
  32598. * @constant
  32599. * @type {LoadingManager}
  32600. */
  32601. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32602. /**
  32603. * Abstract base class for loaders.
  32604. *
  32605. * @abstract
  32606. */
  32607. class Loader {
  32608. /**
  32609. * Constructs a new loader.
  32610. *
  32611. * @param {LoadingManager} [manager] - The loading manager.
  32612. */
  32613. constructor( manager ) {
  32614. /**
  32615. * The loading manager.
  32616. *
  32617. * @type {LoadingManager}
  32618. * @default DefaultLoadingManager
  32619. */
  32620. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32621. /**
  32622. * The crossOrigin string to implement CORS for loading the url from a
  32623. * different domain that allows CORS.
  32624. *
  32625. * @type {string}
  32626. * @default 'anonymous'
  32627. */
  32628. this.crossOrigin = 'anonymous';
  32629. /**
  32630. * Whether the XMLHttpRequest uses credentials.
  32631. *
  32632. * @type {boolean}
  32633. * @default false
  32634. */
  32635. this.withCredentials = false;
  32636. /**
  32637. * The base path from which the asset will be loaded.
  32638. *
  32639. * @type {string}
  32640. */
  32641. this.path = '';
  32642. /**
  32643. * The base path from which additional resources like textures will be loaded.
  32644. *
  32645. * @type {string}
  32646. */
  32647. this.resourcePath = '';
  32648. /**
  32649. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32650. * used in HTTP request.
  32651. *
  32652. * @type {Object<string, any>}
  32653. */
  32654. this.requestHeader = {};
  32655. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32656. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32657. }
  32658. }
  32659. /**
  32660. * This method needs to be implemented by all concrete loaders. It holds the
  32661. * logic for loading assets from the backend.
  32662. *
  32663. * @abstract
  32664. * @param {string} url - The path/URL of the file to be loaded.
  32665. * @param {Function} onLoad - Executed when the loading process has been finished.
  32666. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32667. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32668. */
  32669. load( /* url, onLoad, onProgress, onError */ ) {}
  32670. /**
  32671. * A async version of {@link Loader#load}.
  32672. *
  32673. * @param {string} url - The path/URL of the file to be loaded.
  32674. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32675. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32676. */
  32677. loadAsync( url, onProgress ) {
  32678. const scope = this;
  32679. return new Promise( function ( resolve, reject ) {
  32680. scope.load( url, resolve, onProgress, reject );
  32681. } );
  32682. }
  32683. /**
  32684. * This method needs to be implemented by all concrete loaders. It holds the
  32685. * logic for parsing the asset into three.js entities.
  32686. *
  32687. * @abstract
  32688. * @param {any} data - The data to parse.
  32689. */
  32690. parse( /* data */ ) {}
  32691. /**
  32692. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32693. * from a different domain that allows CORS.
  32694. *
  32695. * @param {string} crossOrigin - The `crossOrigin` value.
  32696. * @return {Loader} A reference to this instance.
  32697. */
  32698. setCrossOrigin( crossOrigin ) {
  32699. this.crossOrigin = crossOrigin;
  32700. return this;
  32701. }
  32702. /**
  32703. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32704. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32705. *
  32706. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32707. *
  32708. * @param {boolean} value - The `withCredentials` value.
  32709. * @return {Loader} A reference to this instance.
  32710. */
  32711. setWithCredentials( value ) {
  32712. this.withCredentials = value;
  32713. return this;
  32714. }
  32715. /**
  32716. * Sets the base path for the asset.
  32717. *
  32718. * @param {string} path - The base path.
  32719. * @return {Loader} A reference to this instance.
  32720. */
  32721. setPath( path ) {
  32722. this.path = path;
  32723. return this;
  32724. }
  32725. /**
  32726. * Sets the base path for dependent resources like textures.
  32727. *
  32728. * @param {string} resourcePath - The resource path.
  32729. * @return {Loader} A reference to this instance.
  32730. */
  32731. setResourcePath( resourcePath ) {
  32732. this.resourcePath = resourcePath;
  32733. return this;
  32734. }
  32735. /**
  32736. * Sets the given request header.
  32737. *
  32738. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32739. * for configuring the HTTP request.
  32740. * @return {Loader} A reference to this instance.
  32741. */
  32742. setRequestHeader( requestHeader ) {
  32743. this.requestHeader = requestHeader;
  32744. return this;
  32745. }
  32746. /**
  32747. * This method can be implemented in loaders for aborting ongoing requests.
  32748. *
  32749. * @abstract
  32750. * @return {Loader} A reference to this instance.
  32751. */
  32752. abort() {
  32753. return this;
  32754. }
  32755. }
  32756. /**
  32757. * Callback for onProgress in loaders.
  32758. *
  32759. * @callback onProgressCallback
  32760. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32761. */
  32762. /**
  32763. * Callback for onError in loaders.
  32764. *
  32765. * @callback onErrorCallback
  32766. * @param {Error} error - The error which occurred during the loading process.
  32767. */
  32768. /**
  32769. * The default material name that is used by loaders
  32770. * when creating materials for loaded 3D objects.
  32771. *
  32772. * Note: Not all loaders might honor this setting.
  32773. *
  32774. * @static
  32775. * @type {string}
  32776. * @default '__DEFAULT'
  32777. */
  32778. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32779. const loading = {};
  32780. class HttpError extends Error {
  32781. constructor( message, response ) {
  32782. super( message );
  32783. this.response = response;
  32784. }
  32785. }
  32786. /**
  32787. * A low level class for loading resources with the Fetch API, used internally by
  32788. * most loaders. It can also be used directly to load any file type that does
  32789. * not have a loader.
  32790. *
  32791. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32792. * once to your application.
  32793. *
  32794. * ```js
  32795. * const loader = new THREE.FileLoader();
  32796. * const data = await loader.loadAsync( 'example.txt' );
  32797. * ```
  32798. *
  32799. * @augments Loader
  32800. */
  32801. class FileLoader extends Loader {
  32802. /**
  32803. * Constructs a new file loader.
  32804. *
  32805. * @param {LoadingManager} [manager] - The loading manager.
  32806. */
  32807. constructor( manager ) {
  32808. super( manager );
  32809. /**
  32810. * The expected mime type. Valid values can be found
  32811. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32812. *
  32813. * @type {string}
  32814. */
  32815. this.mimeType = '';
  32816. /**
  32817. * The expected response type.
  32818. *
  32819. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32820. * @default ''
  32821. */
  32822. this.responseType = '';
  32823. /**
  32824. * Used for aborting requests.
  32825. *
  32826. * @private
  32827. * @type {AbortController}
  32828. */
  32829. this._abortController = new AbortController();
  32830. }
  32831. /**
  32832. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32833. *
  32834. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32835. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32836. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32837. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32838. * @return {any|undefined} The cached resource if available.
  32839. */
  32840. load( url, onLoad, onProgress, onError ) {
  32841. if ( url === undefined ) url = '';
  32842. if ( this.path !== undefined ) url = this.path + url;
  32843. url = this.manager.resolveURL( url );
  32844. const cached = Cache.get( `file:${url}` );
  32845. if ( cached !== undefined ) {
  32846. this.manager.itemStart( url );
  32847. setTimeout( () => {
  32848. if ( onLoad ) onLoad( cached );
  32849. this.manager.itemEnd( url );
  32850. }, 0 );
  32851. return cached;
  32852. }
  32853. // Check if request is duplicate
  32854. if ( loading[ url ] !== undefined ) {
  32855. loading[ url ].push( {
  32856. onLoad: onLoad,
  32857. onProgress: onProgress,
  32858. onError: onError
  32859. } );
  32860. return;
  32861. }
  32862. // Initialise array for duplicate requests
  32863. loading[ url ] = [];
  32864. loading[ url ].push( {
  32865. onLoad: onLoad,
  32866. onProgress: onProgress,
  32867. onError: onError,
  32868. } );
  32869. // create request
  32870. const req = new Request( url, {
  32871. headers: new Headers( this.requestHeader ),
  32872. credentials: this.withCredentials ? 'include' : 'same-origin',
  32873. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32874. } );
  32875. // record states ( avoid data race )
  32876. const mimeType = this.mimeType;
  32877. const responseType = this.responseType;
  32878. // start the fetch
  32879. fetch( req )
  32880. .then( response => {
  32881. if ( response.status === 200 || response.status === 0 ) {
  32882. // Some browsers return HTTP Status 0 when using non-http protocol
  32883. // e.g. 'file://' or 'data://'. Handle as success.
  32884. if ( response.status === 0 ) {
  32885. warn( 'FileLoader: HTTP Status 0 received.' );
  32886. }
  32887. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32888. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32889. return response;
  32890. }
  32891. const callbacks = loading[ url ];
  32892. const reader = response.body.getReader();
  32893. // Nginx needs X-File-Size check
  32894. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32895. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32896. const total = contentLength ? parseInt( contentLength ) : 0;
  32897. const lengthComputable = total !== 0;
  32898. let loaded = 0;
  32899. // periodically read data into the new stream tracking while download progress
  32900. const stream = new ReadableStream( {
  32901. start( controller ) {
  32902. readData();
  32903. function readData() {
  32904. reader.read().then( ( { done, value } ) => {
  32905. if ( done ) {
  32906. controller.close();
  32907. } else {
  32908. loaded += value.byteLength;
  32909. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32910. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32911. const callback = callbacks[ i ];
  32912. if ( callback.onProgress ) callback.onProgress( event );
  32913. }
  32914. controller.enqueue( value );
  32915. readData();
  32916. }
  32917. }, ( e ) => {
  32918. controller.error( e );
  32919. } );
  32920. }
  32921. }
  32922. } );
  32923. return new Response( stream );
  32924. } else {
  32925. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32926. }
  32927. } )
  32928. .then( response => {
  32929. switch ( responseType ) {
  32930. case 'arraybuffer':
  32931. return response.arrayBuffer();
  32932. case 'blob':
  32933. return response.blob();
  32934. case 'document':
  32935. return response.text()
  32936. .then( text => {
  32937. const parser = new DOMParser();
  32938. return parser.parseFromString( text, mimeType );
  32939. } );
  32940. case 'json':
  32941. return response.json();
  32942. default:
  32943. if ( mimeType === '' ) {
  32944. return response.text();
  32945. } else {
  32946. // sniff encoding
  32947. const re = /charset="?([^;"\s]*)"?/i;
  32948. const exec = re.exec( mimeType );
  32949. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32950. const decoder = new TextDecoder( label );
  32951. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32952. }
  32953. }
  32954. } )
  32955. .then( data => {
  32956. // Add to cache only on HTTP success, so that we do not cache
  32957. // error response bodies as proper responses to requests.
  32958. Cache.add( `file:${url}`, data );
  32959. const callbacks = loading[ url ];
  32960. delete loading[ url ];
  32961. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32962. const callback = callbacks[ i ];
  32963. if ( callback.onLoad ) callback.onLoad( data );
  32964. }
  32965. } )
  32966. .catch( err => {
  32967. // Abort errors and other errors are handled the same
  32968. const callbacks = loading[ url ];
  32969. if ( callbacks === undefined ) {
  32970. // When onLoad was called and url was deleted in `loading`
  32971. this.manager.itemError( url );
  32972. throw err;
  32973. }
  32974. delete loading[ url ];
  32975. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32976. const callback = callbacks[ i ];
  32977. if ( callback.onError ) callback.onError( err );
  32978. }
  32979. this.manager.itemError( url );
  32980. } )
  32981. .finally( () => {
  32982. this.manager.itemEnd( url );
  32983. } );
  32984. this.manager.itemStart( url );
  32985. }
  32986. /**
  32987. * Sets the expected response type.
  32988. *
  32989. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32990. * @return {FileLoader} A reference to this file loader.
  32991. */
  32992. setResponseType( value ) {
  32993. this.responseType = value;
  32994. return this;
  32995. }
  32996. /**
  32997. * Sets the expected mime type of the loaded file.
  32998. *
  32999. * @param {string} value - The mime type.
  33000. * @return {FileLoader} A reference to this file loader.
  33001. */
  33002. setMimeType( value ) {
  33003. this.mimeType = value;
  33004. return this;
  33005. }
  33006. /**
  33007. * Aborts ongoing fetch requests.
  33008. *
  33009. * @return {FileLoader} A reference to this instance.
  33010. */
  33011. abort() {
  33012. this._abortController.abort();
  33013. this._abortController = new AbortController();
  33014. return this;
  33015. }
  33016. }
  33017. /**
  33018. * Class for loading animation clips in the JSON format. The files are internally
  33019. * loaded via {@link FileLoader}.
  33020. *
  33021. * ```js
  33022. * const loader = new THREE.AnimationLoader();
  33023. * const animations = await loader.loadAsync( 'animations/animation.js' );
  33024. * ```
  33025. *
  33026. * @augments Loader
  33027. */
  33028. class AnimationLoader extends Loader {
  33029. /**
  33030. * Constructs a new animation loader.
  33031. *
  33032. * @param {LoadingManager} [manager] - The loading manager.
  33033. */
  33034. constructor( manager ) {
  33035. super( manager );
  33036. }
  33037. /**
  33038. * Starts loading from the given URL and pass the loaded animations as an array
  33039. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  33040. *
  33041. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33042. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  33043. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33044. * @param {onErrorCallback} onError - Executed when errors occur.
  33045. */
  33046. load( url, onLoad, onProgress, onError ) {
  33047. const scope = this;
  33048. const loader = new FileLoader( this.manager );
  33049. loader.setPath( this.path );
  33050. loader.setRequestHeader( this.requestHeader );
  33051. loader.setWithCredentials( this.withCredentials );
  33052. loader.load( url, function ( text ) {
  33053. try {
  33054. onLoad( scope.parse( JSON.parse( text ) ) );
  33055. } catch ( e ) {
  33056. if ( onError ) {
  33057. onError( e );
  33058. } else {
  33059. error( e );
  33060. }
  33061. scope.manager.itemError( url );
  33062. }
  33063. }, onProgress, onError );
  33064. }
  33065. /**
  33066. * Parses the given JSON object and returns an array of animation clips.
  33067. *
  33068. * @param {Object} json - The serialized animation clips.
  33069. * @return {Array<AnimationClip>} The parsed animation clips.
  33070. */
  33071. parse( json ) {
  33072. const animations = [];
  33073. for ( let i = 0; i < json.length; i ++ ) {
  33074. const clip = AnimationClip.parse( json[ i ] );
  33075. animations.push( clip );
  33076. }
  33077. return animations;
  33078. }
  33079. }
  33080. /**
  33081. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  33082. * Textures are internally loaded via {@link FileLoader}.
  33083. *
  33084. * Derived classes have to implement the `parse()` method which holds the parsing
  33085. * for the respective format.
  33086. *
  33087. * @abstract
  33088. * @augments Loader
  33089. */
  33090. class CompressedTextureLoader extends Loader {
  33091. /**
  33092. * Constructs a new compressed texture loader.
  33093. *
  33094. * @param {LoadingManager} [manager] - The loading manager.
  33095. */
  33096. constructor( manager ) {
  33097. super( manager );
  33098. }
  33099. /**
  33100. * Starts loading from the given URL and passes the loaded compressed texture
  33101. * to the `onLoad()` callback. The method also returns a new texture object which can
  33102. * directly be used for material creation. If you do it this way, the texture
  33103. * may pop up in your scene once the respective loading process is finished.
  33104. *
  33105. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33106. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  33107. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33108. * @param {onErrorCallback} onError - Executed when errors occur.
  33109. * @return {CompressedTexture} The compressed texture.
  33110. */
  33111. load( url, onLoad, onProgress, onError ) {
  33112. const scope = this;
  33113. const images = [];
  33114. const texture = new CompressedTexture();
  33115. const loader = new FileLoader( this.manager );
  33116. loader.setPath( this.path );
  33117. loader.setResponseType( 'arraybuffer' );
  33118. loader.setRequestHeader( this.requestHeader );
  33119. loader.setWithCredentials( scope.withCredentials );
  33120. let loaded = 0;
  33121. function loadTexture( i ) {
  33122. loader.load( url[ i ], function ( buffer ) {
  33123. const texDatas = scope.parse( buffer, true );
  33124. images[ i ] = {
  33125. width: texDatas.width,
  33126. height: texDatas.height,
  33127. format: texDatas.format,
  33128. mipmaps: texDatas.mipmaps
  33129. };
  33130. loaded += 1;
  33131. if ( loaded === 6 ) {
  33132. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  33133. texture.image = images;
  33134. texture.format = texDatas.format;
  33135. texture.needsUpdate = true;
  33136. if ( onLoad ) onLoad( texture );
  33137. }
  33138. }, onProgress, onError );
  33139. }
  33140. if ( Array.isArray( url ) ) {
  33141. for ( let i = 0, il = url.length; i < il; ++ i ) {
  33142. loadTexture( i );
  33143. }
  33144. } else {
  33145. // compressed cubemap texture stored in a single DDS file
  33146. loader.load( url, function ( buffer ) {
  33147. const texDatas = scope.parse( buffer, true );
  33148. if ( texDatas.isCubemap ) {
  33149. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33150. for ( let f = 0; f < faces; f ++ ) {
  33151. images[ f ] = { mipmaps: [] };
  33152. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33153. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33154. images[ f ].format = texDatas.format;
  33155. images[ f ].width = texDatas.width;
  33156. images[ f ].height = texDatas.height;
  33157. }
  33158. }
  33159. texture.image = images;
  33160. } else {
  33161. texture.image.width = texDatas.width;
  33162. texture.image.height = texDatas.height;
  33163. texture.mipmaps = texDatas.mipmaps;
  33164. }
  33165. if ( texDatas.mipmapCount === 1 ) {
  33166. texture.minFilter = LinearFilter;
  33167. }
  33168. texture.format = texDatas.format;
  33169. texture.needsUpdate = true;
  33170. if ( onLoad ) onLoad( texture );
  33171. }, onProgress, onError );
  33172. }
  33173. return texture;
  33174. }
  33175. }
  33176. const _loading = new WeakMap();
  33177. /**
  33178. * A loader for loading images. The class loads images with the HTML `Image` API.
  33179. *
  33180. * ```js
  33181. * const loader = new THREE.ImageLoader();
  33182. * const image = await loader.loadAsync( 'image.png' );
  33183. * ```
  33184. * Please note that `ImageLoader` has dropped support for progress
  33185. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33186. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33187. *
  33188. * @augments Loader
  33189. */
  33190. class ImageLoader extends Loader {
  33191. /**
  33192. * Constructs a new image loader.
  33193. *
  33194. * @param {LoadingManager} [manager] - The loading manager.
  33195. */
  33196. constructor( manager ) {
  33197. super( manager );
  33198. }
  33199. /**
  33200. * Starts loading from the given URL and passes the loaded image
  33201. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33202. * directly be used for texture creation. If you do it this way, the texture
  33203. * may pop up in your scene once the respective loading process is finished.
  33204. *
  33205. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33206. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33207. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33208. * @param {onErrorCallback} onError - Executed when errors occur.
  33209. * @return {Image} The image.
  33210. */
  33211. load( url, onLoad, onProgress, onError ) {
  33212. if ( this.path !== undefined ) url = this.path + url;
  33213. url = this.manager.resolveURL( url );
  33214. const scope = this;
  33215. const cached = Cache.get( `image:${url}` );
  33216. if ( cached !== undefined ) {
  33217. if ( cached.complete === true ) {
  33218. scope.manager.itemStart( url );
  33219. setTimeout( function () {
  33220. if ( onLoad ) onLoad( cached );
  33221. scope.manager.itemEnd( url );
  33222. }, 0 );
  33223. } else {
  33224. let arr = _loading.get( cached );
  33225. if ( arr === undefined ) {
  33226. arr = [];
  33227. _loading.set( cached, arr );
  33228. }
  33229. arr.push( { onLoad, onError } );
  33230. }
  33231. return cached;
  33232. }
  33233. const image = createElementNS( 'img' );
  33234. function onImageLoad() {
  33235. removeEventListeners();
  33236. if ( onLoad ) onLoad( this );
  33237. //
  33238. const callbacks = _loading.get( this ) || [];
  33239. for ( let i = 0; i < callbacks.length; i ++ ) {
  33240. const callback = callbacks[ i ];
  33241. if ( callback.onLoad ) callback.onLoad( this );
  33242. }
  33243. _loading.delete( this );
  33244. scope.manager.itemEnd( url );
  33245. }
  33246. function onImageError( event ) {
  33247. removeEventListeners();
  33248. if ( onError ) onError( event );
  33249. Cache.remove( `image:${url}` );
  33250. //
  33251. const callbacks = _loading.get( this ) || [];
  33252. for ( let i = 0; i < callbacks.length; i ++ ) {
  33253. const callback = callbacks[ i ];
  33254. if ( callback.onError ) callback.onError( event );
  33255. }
  33256. _loading.delete( this );
  33257. scope.manager.itemError( url );
  33258. scope.manager.itemEnd( url );
  33259. }
  33260. function removeEventListeners() {
  33261. image.removeEventListener( 'load', onImageLoad, false );
  33262. image.removeEventListener( 'error', onImageError, false );
  33263. }
  33264. image.addEventListener( 'load', onImageLoad, false );
  33265. image.addEventListener( 'error', onImageError, false );
  33266. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33267. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33268. }
  33269. Cache.add( `image:${url}`, image );
  33270. scope.manager.itemStart( url );
  33271. image.src = url;
  33272. return image;
  33273. }
  33274. }
  33275. /**
  33276. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33277. *
  33278. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33279. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33280. * like vertical and horizontal cross, column and row layouts are not supported.
  33281. *
  33282. * Note that, by convention, cube maps are specified in a coordinate system
  33283. * in which positive-x is to the right when looking up the positive-z axis --
  33284. * in other words, using a left-handed coordinate system. Since three.js uses
  33285. * a right-handed coordinate system, environment maps used in three.js will
  33286. * have pos-x and neg-x swapped.
  33287. *
  33288. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33289. * is set to `SRGBColorSpace` by default.
  33290. *
  33291. * ```js
  33292. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33293. * const cubeTexture = await loader.loadAsync( [
  33294. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33295. * ] );
  33296. * scene.background = cubeTexture;
  33297. * ```
  33298. *
  33299. * @augments Loader
  33300. */
  33301. class CubeTextureLoader extends Loader {
  33302. /**
  33303. * Constructs a new cube texture loader.
  33304. *
  33305. * @param {LoadingManager} [manager] - The loading manager.
  33306. */
  33307. constructor( manager ) {
  33308. super( manager );
  33309. }
  33310. /**
  33311. * Starts loading from the given URL and pass the fully loaded cube texture
  33312. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33313. * directly be used for material creation. If you do it this way, the cube texture
  33314. * may pop up in your scene once the respective loading process is finished.
  33315. *
  33316. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33317. * cube texture. The urls should be specified in the following order: pos-x,
  33318. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33319. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33320. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33321. * @param {onErrorCallback} onError - Executed when errors occur.
  33322. * @return {CubeTexture} The cube texture.
  33323. */
  33324. load( urls, onLoad, onProgress, onError ) {
  33325. const texture = new CubeTexture();
  33326. texture.colorSpace = SRGBColorSpace;
  33327. const loader = new ImageLoader( this.manager );
  33328. loader.setCrossOrigin( this.crossOrigin );
  33329. loader.setPath( this.path );
  33330. let loaded = 0;
  33331. function loadTexture( i ) {
  33332. loader.load( urls[ i ], function ( image ) {
  33333. texture.images[ i ] = image;
  33334. loaded ++;
  33335. if ( loaded === 6 ) {
  33336. texture.needsUpdate = true;
  33337. if ( onLoad ) onLoad( texture );
  33338. }
  33339. }, undefined, onError );
  33340. }
  33341. for ( let i = 0; i < urls.length; ++ i ) {
  33342. loadTexture( i );
  33343. }
  33344. return texture;
  33345. }
  33346. }
  33347. /**
  33348. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33349. * Textures are internally loaded via {@link FileLoader}.
  33350. *
  33351. * Derived classes have to implement the `parse()` method which holds the parsing
  33352. * for the respective format.
  33353. *
  33354. * @abstract
  33355. * @augments Loader
  33356. */
  33357. class DataTextureLoader extends Loader {
  33358. /**
  33359. * Constructs a new data texture loader.
  33360. *
  33361. * @param {LoadingManager} [manager] - The loading manager.
  33362. */
  33363. constructor( manager ) {
  33364. super( manager );
  33365. }
  33366. /**
  33367. * Starts loading from the given URL and passes the loaded data texture
  33368. * to the `onLoad()` callback. The method also returns a new texture object which can
  33369. * directly be used for material creation. If you do it this way, the texture
  33370. * may pop up in your scene once the respective loading process is finished.
  33371. *
  33372. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33373. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33374. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33375. * @param {onErrorCallback} onError - Executed when errors occur.
  33376. * @return {DataTexture} The data texture.
  33377. */
  33378. load( url, onLoad, onProgress, onError ) {
  33379. const scope = this;
  33380. const texture = new DataTexture();
  33381. const loader = new FileLoader( this.manager );
  33382. loader.setResponseType( 'arraybuffer' );
  33383. loader.setRequestHeader( this.requestHeader );
  33384. loader.setPath( this.path );
  33385. loader.setWithCredentials( scope.withCredentials );
  33386. loader.load( url, function ( buffer ) {
  33387. let texData;
  33388. try {
  33389. texData = scope.parse( buffer );
  33390. } catch ( error ) {
  33391. if ( onError !== undefined ) {
  33392. onError( error );
  33393. } else {
  33394. error( error );
  33395. return;
  33396. }
  33397. }
  33398. if ( texData.image !== undefined ) {
  33399. texture.image = texData.image;
  33400. } else if ( texData.data !== undefined ) {
  33401. texture.image.width = texData.width;
  33402. texture.image.height = texData.height;
  33403. texture.image.data = texData.data;
  33404. }
  33405. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33406. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33407. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33408. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33409. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33410. if ( texData.colorSpace !== undefined ) {
  33411. texture.colorSpace = texData.colorSpace;
  33412. }
  33413. if ( texData.flipY !== undefined ) {
  33414. texture.flipY = texData.flipY;
  33415. }
  33416. if ( texData.format !== undefined ) {
  33417. texture.format = texData.format;
  33418. }
  33419. if ( texData.type !== undefined ) {
  33420. texture.type = texData.type;
  33421. }
  33422. if ( texData.mipmaps !== undefined ) {
  33423. texture.mipmaps = texData.mipmaps;
  33424. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33425. }
  33426. if ( texData.mipmapCount === 1 ) {
  33427. texture.minFilter = LinearFilter;
  33428. }
  33429. if ( texData.generateMipmaps !== undefined ) {
  33430. texture.generateMipmaps = texData.generateMipmaps;
  33431. }
  33432. texture.needsUpdate = true;
  33433. if ( onLoad ) onLoad( texture, texData );
  33434. }, onProgress, onError );
  33435. return texture;
  33436. }
  33437. }
  33438. /**
  33439. * Class for loading textures. Images are internally
  33440. * loaded via {@link ImageLoader}.
  33441. *
  33442. * ```js
  33443. * const loader = new THREE.TextureLoader();
  33444. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33445. *
  33446. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33447. * ```
  33448. * Please note that `TextureLoader` has dropped support for progress
  33449. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33450. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33451. *
  33452. * @augments Loader
  33453. */
  33454. class TextureLoader extends Loader {
  33455. /**
  33456. * Constructs a new texture loader.
  33457. *
  33458. * @param {LoadingManager} [manager] - The loading manager.
  33459. */
  33460. constructor( manager ) {
  33461. super( manager );
  33462. }
  33463. /**
  33464. * Starts loading from the given URL and pass the fully loaded texture
  33465. * to the `onLoad()` callback. The method also returns a new texture object which can
  33466. * directly be used for material creation. If you do it this way, the texture
  33467. * may pop up in your scene once the respective loading process is finished.
  33468. *
  33469. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33470. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33471. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33472. * @param {onErrorCallback} onError - Executed when errors occur.
  33473. * @return {Texture} The texture.
  33474. */
  33475. load( url, onLoad, onProgress, onError ) {
  33476. const texture = new Texture();
  33477. const loader = new ImageLoader( this.manager );
  33478. loader.setCrossOrigin( this.crossOrigin );
  33479. loader.setPath( this.path );
  33480. loader.load( url, function ( image ) {
  33481. texture.image = image;
  33482. texture.needsUpdate = true;
  33483. if ( onLoad !== undefined ) {
  33484. onLoad( texture );
  33485. }
  33486. }, onProgress, onError );
  33487. return texture;
  33488. }
  33489. }
  33490. /**
  33491. * Abstract base class for lights - all other light types inherit the
  33492. * properties and methods described here.
  33493. *
  33494. * @abstract
  33495. * @augments Object3D
  33496. */
  33497. class Light extends Object3D {
  33498. /**
  33499. * Constructs a new light.
  33500. *
  33501. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33502. * @param {number} [intensity=1] - The light's strength/intensity.
  33503. */
  33504. constructor( color, intensity = 1 ) {
  33505. super();
  33506. /**
  33507. * This flag can be used for type testing.
  33508. *
  33509. * @type {boolean}
  33510. * @readonly
  33511. * @default true
  33512. */
  33513. this.isLight = true;
  33514. this.type = 'Light';
  33515. /**
  33516. * The light's color.
  33517. *
  33518. * @type {Color}
  33519. */
  33520. this.color = new Color( color );
  33521. /**
  33522. * The light's intensity.
  33523. *
  33524. * @type {number}
  33525. * @default 1
  33526. */
  33527. this.intensity = intensity;
  33528. }
  33529. /**
  33530. * Frees the GPU-related resources allocated by this instance. Call this
  33531. * method whenever this instance is no longer used in your app.
  33532. */
  33533. dispose() {
  33534. this.dispatchEvent( { type: 'dispose' } );
  33535. }
  33536. copy( source, recursive ) {
  33537. super.copy( source, recursive );
  33538. this.color.copy( source.color );
  33539. this.intensity = source.intensity;
  33540. return this;
  33541. }
  33542. toJSON( meta ) {
  33543. const data = super.toJSON( meta );
  33544. data.object.color = this.color.getHex();
  33545. data.object.intensity = this.intensity;
  33546. return data;
  33547. }
  33548. }
  33549. /**
  33550. * A light source positioned directly above the scene, with color fading from
  33551. * the sky color to the ground color.
  33552. *
  33553. * This light cannot be used to cast shadows.
  33554. *
  33555. * ```js
  33556. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33557. * scene.add( light );
  33558. * ```
  33559. *
  33560. * @augments Light
  33561. */
  33562. class HemisphereLight extends Light {
  33563. /**
  33564. * Constructs a new hemisphere light.
  33565. *
  33566. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33567. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33568. * @param {number} [intensity=1] - The light's strength/intensity.
  33569. */
  33570. constructor( skyColor, groundColor, intensity ) {
  33571. super( skyColor, intensity );
  33572. /**
  33573. * This flag can be used for type testing.
  33574. *
  33575. * @type {boolean}
  33576. * @readonly
  33577. * @default true
  33578. */
  33579. this.isHemisphereLight = true;
  33580. this.type = 'HemisphereLight';
  33581. this.position.copy( Object3D.DEFAULT_UP );
  33582. this.updateMatrix();
  33583. /**
  33584. * The light's ground color.
  33585. *
  33586. * @type {Color}
  33587. */
  33588. this.groundColor = new Color( groundColor );
  33589. }
  33590. copy( source, recursive ) {
  33591. super.copy( source, recursive );
  33592. this.groundColor.copy( source.groundColor );
  33593. return this;
  33594. }
  33595. toJSON( meta ) {
  33596. const data = super.toJSON( meta );
  33597. data.object.groundColor = this.groundColor.getHex();
  33598. return data;
  33599. }
  33600. }
  33601. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33602. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33603. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33604. /**
  33605. * Abstract base class for light shadow classes. These classes
  33606. * represent the shadow configuration for different light types.
  33607. *
  33608. * @abstract
  33609. */
  33610. class LightShadow {
  33611. /**
  33612. * Constructs a new light shadow.
  33613. *
  33614. * @param {Camera} camera - The light's view of the world.
  33615. */
  33616. constructor( camera ) {
  33617. /**
  33618. * The light's view of the world.
  33619. *
  33620. * @type {Camera}
  33621. */
  33622. this.camera = camera;
  33623. /**
  33624. * The intensity of the shadow. The default is `1`.
  33625. * Valid values are in the range `[0, 1]`.
  33626. *
  33627. * @type {number}
  33628. * @default 1
  33629. */
  33630. this.intensity = 1;
  33631. /**
  33632. * Shadow map bias, how much to add or subtract from the normalized depth
  33633. * when deciding whether a surface is in shadow.
  33634. *
  33635. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33636. * may help reduce artifacts in shadows.
  33637. *
  33638. * @type {number}
  33639. * @default 0
  33640. */
  33641. this.bias = 0;
  33642. /**
  33643. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33644. *
  33645. * If a bias node is defined, `bias` has no effect.
  33646. *
  33647. * @type {?Node<float>}
  33648. * @default null
  33649. */
  33650. this.biasNode = null;
  33651. /**
  33652. * Defines how much the position used to query the shadow map is offset along
  33653. * the object normal. The default is `0`. Increasing this value can be used to
  33654. * reduce shadow acne especially in large scenes where light shines onto
  33655. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33656. *
  33657. * @type {number}
  33658. * @default 0
  33659. */
  33660. this.normalBias = 0;
  33661. /**
  33662. * Setting this to values greater than 1 will blur the edges of the shadow.
  33663. * High values will cause unwanted banding effects in the shadows - a greater
  33664. * map size will allow for a higher value to be used here before these effects
  33665. * become visible.
  33666. *
  33667. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33668. *
  33669. * @type {number}
  33670. * @default 1
  33671. */
  33672. this.radius = 1;
  33673. /**
  33674. * The amount of samples to use when blurring a VSM shadow map.
  33675. *
  33676. * @type {number}
  33677. * @default 8
  33678. */
  33679. this.blurSamples = 8;
  33680. /**
  33681. * Defines the width and height of the shadow map. Higher values give better quality
  33682. * shadows at the cost of computation time. Values must be powers of two.
  33683. *
  33684. * @type {Vector2}
  33685. * @default (512,512)
  33686. */
  33687. this.mapSize = new Vector2( 512, 512 );
  33688. /**
  33689. * The type of shadow texture. The default is `UnsignedByteType`.
  33690. *
  33691. * @type {number}
  33692. * @default UnsignedByteType
  33693. */
  33694. this.mapType = UnsignedByteType;
  33695. /**
  33696. * The depth map generated using the internal camera; a location beyond a
  33697. * pixel's depth is in shadow. Computed internally during rendering.
  33698. *
  33699. * @type {?RenderTarget}
  33700. * @default null
  33701. */
  33702. this.map = null;
  33703. /**
  33704. * The distribution map generated using the internal camera; an occlusion is
  33705. * calculated based on the distribution of depths. Computed internally during
  33706. * rendering.
  33707. *
  33708. * @type {?RenderTarget}
  33709. * @default null
  33710. */
  33711. this.mapPass = null;
  33712. /**
  33713. * Model to shadow camera space, to compute location and depth in shadow map.
  33714. * This is computed internally during rendering.
  33715. *
  33716. * @type {Matrix4}
  33717. */
  33718. this.matrix = new Matrix4();
  33719. /**
  33720. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33721. * lighting / shadows, you may set this to `false`.
  33722. *
  33723. * @type {boolean}
  33724. * @default true
  33725. */
  33726. this.autoUpdate = true;
  33727. /**
  33728. * When set to `true`, shadow maps will be updated in the next `render` call.
  33729. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33730. * set this property to `true` and then make a render call to update the light's shadow.
  33731. *
  33732. * @type {boolean}
  33733. * @default false
  33734. */
  33735. this.needsUpdate = false;
  33736. this._frustum = new Frustum();
  33737. this._frameExtents = new Vector2( 1, 1 );
  33738. this._viewportCount = 1;
  33739. this._viewports = [
  33740. new Vector4( 0, 0, 1, 1 )
  33741. ];
  33742. }
  33743. /**
  33744. * Used internally by the renderer to get the number of viewports that need
  33745. * to be rendered for this shadow.
  33746. *
  33747. * @return {number} The viewport count.
  33748. */
  33749. getViewportCount() {
  33750. return this._viewportCount;
  33751. }
  33752. /**
  33753. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33754. *
  33755. * @return {Frustum} The shadow camera frustum.
  33756. */
  33757. getFrustum() {
  33758. return this._frustum;
  33759. }
  33760. /**
  33761. * Update the matrices for the camera and shadow, used internally by the renderer.
  33762. *
  33763. * @param {Light} light - The light for which the shadow is being rendered.
  33764. */
  33765. updateMatrices( light ) {
  33766. const shadowCamera = this.camera;
  33767. const shadowMatrix = this.matrix;
  33768. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33769. shadowCamera.position.copy( _lightPositionWorld$1 );
  33770. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33771. shadowCamera.lookAt( _lookTarget$1 );
  33772. shadowCamera.updateMatrixWorld();
  33773. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33774. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33775. if ( shadowCamera.reversedDepth ) {
  33776. shadowMatrix.set(
  33777. 0.5, 0.0, 0.0, 0.5,
  33778. 0.0, 0.5, 0.0, 0.5,
  33779. 0.0, 0.0, 1.0, 0.0,
  33780. 0.0, 0.0, 0.0, 1.0
  33781. );
  33782. } else {
  33783. shadowMatrix.set(
  33784. 0.5, 0.0, 0.0, 0.5,
  33785. 0.0, 0.5, 0.0, 0.5,
  33786. 0.0, 0.0, 0.5, 0.5,
  33787. 0.0, 0.0, 0.0, 1.0
  33788. );
  33789. }
  33790. shadowMatrix.multiply( _projScreenMatrix$1 );
  33791. }
  33792. /**
  33793. * Returns a viewport definition for the given viewport index.
  33794. *
  33795. * @param {number} viewportIndex - The viewport index.
  33796. * @return {Vector4} The viewport.
  33797. */
  33798. getViewport( viewportIndex ) {
  33799. return this._viewports[ viewportIndex ];
  33800. }
  33801. /**
  33802. * Returns the frame extends.
  33803. *
  33804. * @return {Vector2} The frame extends.
  33805. */
  33806. getFrameExtents() {
  33807. return this._frameExtents;
  33808. }
  33809. /**
  33810. * Frees the GPU-related resources allocated by this instance. Call this
  33811. * method whenever this instance is no longer used in your app.
  33812. */
  33813. dispose() {
  33814. if ( this.map ) {
  33815. this.map.dispose();
  33816. }
  33817. if ( this.mapPass ) {
  33818. this.mapPass.dispose();
  33819. }
  33820. }
  33821. /**
  33822. * Copies the values of the given light shadow instance to this instance.
  33823. *
  33824. * @param {LightShadow} source - The light shadow to copy.
  33825. * @return {LightShadow} A reference to this light shadow instance.
  33826. */
  33827. copy( source ) {
  33828. this.camera = source.camera.clone();
  33829. this.intensity = source.intensity;
  33830. this.bias = source.bias;
  33831. this.radius = source.radius;
  33832. this.autoUpdate = source.autoUpdate;
  33833. this.needsUpdate = source.needsUpdate;
  33834. this.normalBias = source.normalBias;
  33835. this.blurSamples = source.blurSamples;
  33836. this.mapSize.copy( source.mapSize );
  33837. this.biasNode = source.biasNode;
  33838. return this;
  33839. }
  33840. /**
  33841. * Returns a new light shadow instance with copied values from this instance.
  33842. *
  33843. * @return {LightShadow} A clone of this instance.
  33844. */
  33845. clone() {
  33846. return new this.constructor().copy( this );
  33847. }
  33848. /**
  33849. * Serializes the light shadow into JSON.
  33850. *
  33851. * @return {Object} A JSON object representing the serialized light shadow.
  33852. * @see {@link ObjectLoader#parse}
  33853. */
  33854. toJSON() {
  33855. const object = {};
  33856. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33857. if ( this.bias !== 0 ) object.bias = this.bias;
  33858. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33859. if ( this.radius !== 1 ) object.radius = this.radius;
  33860. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33861. object.camera = this.camera.toJSON( false ).object;
  33862. delete object.camera.matrix;
  33863. return object;
  33864. }
  33865. }
  33866. /**
  33867. * Represents the shadow configuration of directional lights.
  33868. *
  33869. * @augments LightShadow
  33870. */
  33871. class SpotLightShadow extends LightShadow {
  33872. /**
  33873. * Constructs a new spot light shadow.
  33874. */
  33875. constructor() {
  33876. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33877. /**
  33878. * This flag can be used for type testing.
  33879. *
  33880. * @type {boolean}
  33881. * @readonly
  33882. * @default true
  33883. */
  33884. this.isSpotLightShadow = true;
  33885. /**
  33886. * Used to focus the shadow camera. The camera's field of view is set as a
  33887. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33888. *
  33889. * @type {number}
  33890. * @default 1
  33891. */
  33892. this.focus = 1;
  33893. /**
  33894. * Texture aspect ratio.
  33895. *
  33896. * @type {number}
  33897. * @default 1
  33898. */
  33899. this.aspect = 1;
  33900. }
  33901. updateMatrices( light ) {
  33902. const camera = this.camera;
  33903. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33904. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33905. const far = light.distance || camera.far;
  33906. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33907. camera.fov = fov;
  33908. camera.aspect = aspect;
  33909. camera.far = far;
  33910. camera.updateProjectionMatrix();
  33911. }
  33912. super.updateMatrices( light );
  33913. }
  33914. copy( source ) {
  33915. super.copy( source );
  33916. this.focus = source.focus;
  33917. return this;
  33918. }
  33919. }
  33920. /**
  33921. * This light gets emitted from a single point in one direction, along a cone
  33922. * that increases in size the further from the light it gets.
  33923. *
  33924. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33925. *
  33926. * ```js
  33927. * // white spotlight shining from the side, modulated by a texture
  33928. * const spotLight = new THREE.SpotLight( 0xffffff );
  33929. * spotLight.position.set( 100, 1000, 100 );
  33930. * spotLight.map = new THREE.TextureLoader().load( url );
  33931. *
  33932. * spotLight.castShadow = true;
  33933. * spotLight.shadow.mapSize.width = 1024;
  33934. * spotLight.shadow.mapSize.height = 1024;
  33935. * spotLight.shadow.camera.near = 500;
  33936. * spotLight.shadow.camera.far = 4000;
  33937. * spotLight.shadow.camera.fov = 30;s
  33938. * ```
  33939. *
  33940. * @augments Light
  33941. */
  33942. class SpotLight extends Light {
  33943. /**
  33944. * Constructs a new spot light.
  33945. *
  33946. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33947. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33948. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33949. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33950. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33951. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33952. */
  33953. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33954. super( color, intensity );
  33955. /**
  33956. * This flag can be used for type testing.
  33957. *
  33958. * @type {boolean}
  33959. * @readonly
  33960. * @default true
  33961. */
  33962. this.isSpotLight = true;
  33963. this.type = 'SpotLight';
  33964. this.position.copy( Object3D.DEFAULT_UP );
  33965. this.updateMatrix();
  33966. /**
  33967. * The spot light points from its position to the
  33968. * target's position.
  33969. *
  33970. * For the target's position to be changed to anything other
  33971. * than the default, it must be added to the scene.
  33972. *
  33973. * It is also possible to set the target to be another 3D object
  33974. * in the scene. The light will now track the target object.
  33975. *
  33976. * @type {Object3D}
  33977. */
  33978. this.target = new Object3D();
  33979. /**
  33980. * Maximum range of the light. `0` means no limit.
  33981. *
  33982. * @type {number}
  33983. * @default 0
  33984. */
  33985. this.distance = distance;
  33986. /**
  33987. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33988. *
  33989. * @type {number}
  33990. * @default Math.PI/3
  33991. */
  33992. this.angle = angle;
  33993. /**
  33994. * Percent of the spotlight cone that is attenuated due to penumbra.
  33995. * Value range is `[0,1]`.
  33996. *
  33997. * @type {number}
  33998. * @default 0
  33999. */
  34000. this.penumbra = penumbra;
  34001. /**
  34002. * The amount the light dims along the distance of the light. In context of
  34003. * physically-correct rendering the default value should not be changed.
  34004. *
  34005. * @type {number}
  34006. * @default 2
  34007. */
  34008. this.decay = decay;
  34009. /**
  34010. * A texture used to modulate the color of the light. The spot light
  34011. * color is mixed with the RGB value of this texture, with a ratio
  34012. * corresponding to its alpha value. The cookie-like masking effect is
  34013. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  34014. *
  34015. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  34016. *
  34017. * @type {?Texture}
  34018. * @default null
  34019. */
  34020. this.map = null;
  34021. /**
  34022. * This property holds the light's shadow configuration.
  34023. *
  34024. * @type {SpotLightShadow}
  34025. */
  34026. this.shadow = new SpotLightShadow();
  34027. }
  34028. /**
  34029. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34030. * Changing the power will also change the light's intensity.
  34031. *
  34032. * @type {number}
  34033. */
  34034. get power() {
  34035. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34036. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  34037. return this.intensity * Math.PI;
  34038. }
  34039. set power( power ) {
  34040. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34041. this.intensity = power / Math.PI;
  34042. }
  34043. dispose() {
  34044. super.dispose();
  34045. this.shadow.dispose();
  34046. }
  34047. copy( source, recursive ) {
  34048. super.copy( source, recursive );
  34049. this.distance = source.distance;
  34050. this.angle = source.angle;
  34051. this.penumbra = source.penumbra;
  34052. this.decay = source.decay;
  34053. this.target = source.target.clone();
  34054. this.map = source.map;
  34055. this.shadow = source.shadow.clone();
  34056. return this;
  34057. }
  34058. toJSON( meta ) {
  34059. const data = super.toJSON( meta );
  34060. data.object.distance = this.distance;
  34061. data.object.angle = this.angle;
  34062. data.object.decay = this.decay;
  34063. data.object.penumbra = this.penumbra;
  34064. data.object.target = this.target.uuid;
  34065. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  34066. data.object.shadow = this.shadow.toJSON();
  34067. return data;
  34068. }
  34069. }
  34070. /**
  34071. * Represents the shadow configuration of point lights.
  34072. *
  34073. * @augments LightShadow
  34074. */
  34075. class PointLightShadow extends LightShadow {
  34076. /**
  34077. * Constructs a new point light shadow.
  34078. */
  34079. constructor() {
  34080. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  34081. /**
  34082. * This flag can be used for type testing.
  34083. *
  34084. * @type {boolean}
  34085. * @readonly
  34086. * @default true
  34087. */
  34088. this.isPointLightShadow = true;
  34089. }
  34090. }
  34091. /**
  34092. * A light that gets emitted from a single point in all directions. A common
  34093. * use case for this is to replicate the light emitted from a bare
  34094. * lightbulb.
  34095. *
  34096. * This light can cast shadows - see the {@link PointLightShadow} for details.
  34097. *
  34098. * ```js
  34099. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  34100. * light.position.set( 50, 50, 50 );
  34101. * scene.add( light );
  34102. * ```
  34103. *
  34104. * @augments Light
  34105. */
  34106. class PointLight extends Light {
  34107. /**
  34108. * Constructs a new point light.
  34109. *
  34110. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34111. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34112. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34113. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34114. */
  34115. constructor( color, intensity, distance = 0, decay = 2 ) {
  34116. super( color, intensity );
  34117. /**
  34118. * This flag can be used for type testing.
  34119. *
  34120. * @type {boolean}
  34121. * @readonly
  34122. * @default true
  34123. */
  34124. this.isPointLight = true;
  34125. this.type = 'PointLight';
  34126. /**
  34127. * When distance is zero, light will attenuate according to inverse-square
  34128. * law to infinite distance. When distance is non-zero, light will attenuate
  34129. * according to inverse-square law until near the distance cutoff, where it
  34130. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  34131. * physically correct.
  34132. *
  34133. * @type {number}
  34134. * @default 0
  34135. */
  34136. this.distance = distance;
  34137. /**
  34138. * The amount the light dims along the distance of the light. In context of
  34139. * physically-correct rendering the default value should not be changed.
  34140. *
  34141. * @type {number}
  34142. * @default 2
  34143. */
  34144. this.decay = decay;
  34145. /**
  34146. * This property holds the light's shadow configuration.
  34147. *
  34148. * @type {PointLightShadow}
  34149. */
  34150. this.shadow = new PointLightShadow();
  34151. }
  34152. /**
  34153. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34154. * Changing the power will also change the light's intensity.
  34155. *
  34156. * @type {number}
  34157. */
  34158. get power() {
  34159. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34160. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34161. return this.intensity * 4 * Math.PI;
  34162. }
  34163. set power( power ) {
  34164. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34165. this.intensity = power / ( 4 * Math.PI );
  34166. }
  34167. dispose() {
  34168. super.dispose();
  34169. this.shadow.dispose();
  34170. }
  34171. copy( source, recursive ) {
  34172. super.copy( source, recursive );
  34173. this.distance = source.distance;
  34174. this.decay = source.decay;
  34175. this.shadow = source.shadow.clone();
  34176. return this;
  34177. }
  34178. toJSON( meta ) {
  34179. const data = super.toJSON( meta );
  34180. data.object.distance = this.distance;
  34181. data.object.decay = this.decay;
  34182. data.object.shadow = this.shadow.toJSON();
  34183. return data;
  34184. }
  34185. }
  34186. /**
  34187. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34188. *
  34189. * In this projection mode, an object's size in the rendered image stays
  34190. * constant regardless of its distance from the camera. This can be useful
  34191. * for rendering 2D scenes and UI elements, amongst other things.
  34192. *
  34193. * ```js
  34194. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34195. * scene.add( camera );
  34196. * ```
  34197. *
  34198. * @augments Camera
  34199. */
  34200. class OrthographicCamera extends Camera {
  34201. /**
  34202. * Constructs a new orthographic camera.
  34203. *
  34204. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34205. * @param {number} [right=1] - The right plane of the camera's frustum.
  34206. * @param {number} [top=1] - The top plane of the camera's frustum.
  34207. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34208. * @param {number} [near=0.1] - The camera's near plane.
  34209. * @param {number} [far=2000] - The camera's far plane.
  34210. */
  34211. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34212. super();
  34213. /**
  34214. * This flag can be used for type testing.
  34215. *
  34216. * @type {boolean}
  34217. * @readonly
  34218. * @default true
  34219. */
  34220. this.isOrthographicCamera = true;
  34221. this.type = 'OrthographicCamera';
  34222. /**
  34223. * The zoom factor of the camera.
  34224. *
  34225. * @type {number}
  34226. * @default 1
  34227. */
  34228. this.zoom = 1;
  34229. /**
  34230. * Represents the frustum window specification. This property should not be edited
  34231. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34232. *
  34233. * @type {?Object}
  34234. * @default null
  34235. */
  34236. this.view = null;
  34237. /**
  34238. * The left plane of the camera's frustum.
  34239. *
  34240. * @type {number}
  34241. * @default -1
  34242. */
  34243. this.left = left;
  34244. /**
  34245. * The right plane of the camera's frustum.
  34246. *
  34247. * @type {number}
  34248. * @default 1
  34249. */
  34250. this.right = right;
  34251. /**
  34252. * The top plane of the camera's frustum.
  34253. *
  34254. * @type {number}
  34255. * @default 1
  34256. */
  34257. this.top = top;
  34258. /**
  34259. * The bottom plane of the camera's frustum.
  34260. *
  34261. * @type {number}
  34262. * @default -1
  34263. */
  34264. this.bottom = bottom;
  34265. /**
  34266. * The camera's near plane. The valid range is greater than `0`
  34267. * and less than the current value of {@link OrthographicCamera#far}.
  34268. *
  34269. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34270. * valid value for an orthographic camera's near plane.
  34271. *
  34272. * @type {number}
  34273. * @default 0.1
  34274. */
  34275. this.near = near;
  34276. /**
  34277. * The camera's far plane. Must be greater than the
  34278. * current value of {@link OrthographicCamera#near}.
  34279. *
  34280. * @type {number}
  34281. * @default 2000
  34282. */
  34283. this.far = far;
  34284. this.updateProjectionMatrix();
  34285. }
  34286. copy( source, recursive ) {
  34287. super.copy( source, recursive );
  34288. this.left = source.left;
  34289. this.right = source.right;
  34290. this.top = source.top;
  34291. this.bottom = source.bottom;
  34292. this.near = source.near;
  34293. this.far = source.far;
  34294. this.zoom = source.zoom;
  34295. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34296. return this;
  34297. }
  34298. /**
  34299. * Sets an offset in a larger frustum. This is useful for multi-window or
  34300. * multi-monitor/multi-machine setups.
  34301. *
  34302. * @param {number} fullWidth - The full width of multiview setup.
  34303. * @param {number} fullHeight - The full height of multiview setup.
  34304. * @param {number} x - The horizontal offset of the subcamera.
  34305. * @param {number} y - The vertical offset of the subcamera.
  34306. * @param {number} width - The width of subcamera.
  34307. * @param {number} height - The height of subcamera.
  34308. * @see {@link PerspectiveCamera#setViewOffset}
  34309. */
  34310. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34311. if ( this.view === null ) {
  34312. this.view = {
  34313. enabled: true,
  34314. fullWidth: 1,
  34315. fullHeight: 1,
  34316. offsetX: 0,
  34317. offsetY: 0,
  34318. width: 1,
  34319. height: 1
  34320. };
  34321. }
  34322. this.view.enabled = true;
  34323. this.view.fullWidth = fullWidth;
  34324. this.view.fullHeight = fullHeight;
  34325. this.view.offsetX = x;
  34326. this.view.offsetY = y;
  34327. this.view.width = width;
  34328. this.view.height = height;
  34329. this.updateProjectionMatrix();
  34330. }
  34331. /**
  34332. * Removes the view offset from the projection matrix.
  34333. */
  34334. clearViewOffset() {
  34335. if ( this.view !== null ) {
  34336. this.view.enabled = false;
  34337. }
  34338. this.updateProjectionMatrix();
  34339. }
  34340. /**
  34341. * Updates the camera's projection matrix. Must be called after any change of
  34342. * camera properties.
  34343. */
  34344. updateProjectionMatrix() {
  34345. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34346. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34347. const cx = ( this.right + this.left ) / 2;
  34348. const cy = ( this.top + this.bottom ) / 2;
  34349. let left = cx - dx;
  34350. let right = cx + dx;
  34351. let top = cy + dy;
  34352. let bottom = cy - dy;
  34353. if ( this.view !== null && this.view.enabled ) {
  34354. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34355. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34356. left += scaleW * this.view.offsetX;
  34357. right = left + scaleW * this.view.width;
  34358. top -= scaleH * this.view.offsetY;
  34359. bottom = top - scaleH * this.view.height;
  34360. }
  34361. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34362. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34363. }
  34364. toJSON( meta ) {
  34365. const data = super.toJSON( meta );
  34366. data.object.zoom = this.zoom;
  34367. data.object.left = this.left;
  34368. data.object.right = this.right;
  34369. data.object.top = this.top;
  34370. data.object.bottom = this.bottom;
  34371. data.object.near = this.near;
  34372. data.object.far = this.far;
  34373. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34374. return data;
  34375. }
  34376. }
  34377. /**
  34378. * Represents the shadow configuration of directional lights.
  34379. *
  34380. * @augments LightShadow
  34381. */
  34382. class DirectionalLightShadow extends LightShadow {
  34383. /**
  34384. * Constructs a new directional light shadow.
  34385. */
  34386. constructor() {
  34387. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34388. /**
  34389. * This flag can be used for type testing.
  34390. *
  34391. * @type {boolean}
  34392. * @readonly
  34393. * @default true
  34394. */
  34395. this.isDirectionalLightShadow = true;
  34396. }
  34397. }
  34398. /**
  34399. * A light that gets emitted in a specific direction. This light will behave
  34400. * as though it is infinitely far away and the rays produced from it are all
  34401. * parallel. The common use case for this is to simulate daylight; the sun is
  34402. * far enough away that its position can be considered to be infinite, and
  34403. * all light rays coming from it are parallel.
  34404. *
  34405. * A common point of confusion for directional lights is that setting the
  34406. * rotation has no effect. This is because three.js's DirectionalLight is the
  34407. * equivalent to what is often called a 'Target Direct Light' in other
  34408. * applications.
  34409. *
  34410. * This means that its direction is calculated as pointing from the light's
  34411. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34412. * (as opposed to a 'Free Direct Light' that just has a rotation
  34413. * component).
  34414. *
  34415. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34416. *
  34417. * ```js
  34418. * // White directional light at half intensity shining from the top.
  34419. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34420. * scene.add( directionalLight );
  34421. * ```
  34422. *
  34423. * @augments Light
  34424. */
  34425. class DirectionalLight extends Light {
  34426. /**
  34427. * Constructs a new directional light.
  34428. *
  34429. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34430. * @param {number} [intensity=1] - The light's strength/intensity.
  34431. */
  34432. constructor( color, intensity ) {
  34433. super( color, intensity );
  34434. /**
  34435. * This flag can be used for type testing.
  34436. *
  34437. * @type {boolean}
  34438. * @readonly
  34439. * @default true
  34440. */
  34441. this.isDirectionalLight = true;
  34442. this.type = 'DirectionalLight';
  34443. this.position.copy( Object3D.DEFAULT_UP );
  34444. this.updateMatrix();
  34445. /**
  34446. * The directional light points from its position to the
  34447. * target's position.
  34448. *
  34449. * For the target's position to be changed to anything other
  34450. * than the default, it must be added to the scene.
  34451. *
  34452. * It is also possible to set the target to be another 3D object
  34453. * in the scene. The light will now track the target object.
  34454. *
  34455. * @type {Object3D}
  34456. */
  34457. this.target = new Object3D();
  34458. /**
  34459. * This property holds the light's shadow configuration.
  34460. *
  34461. * @type {DirectionalLightShadow}
  34462. */
  34463. this.shadow = new DirectionalLightShadow();
  34464. }
  34465. dispose() {
  34466. super.dispose();
  34467. this.shadow.dispose();
  34468. }
  34469. copy( source ) {
  34470. super.copy( source );
  34471. this.target = source.target.clone();
  34472. this.shadow = source.shadow.clone();
  34473. return this;
  34474. }
  34475. toJSON( meta ) {
  34476. const data = super.toJSON( meta );
  34477. data.object.shadow = this.shadow.toJSON();
  34478. data.object.target = this.target.uuid;
  34479. return data;
  34480. }
  34481. }
  34482. /**
  34483. * This light globally illuminates all objects in the scene equally.
  34484. *
  34485. * It cannot be used to cast shadows as it does not have a direction.
  34486. *
  34487. * ```js
  34488. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34489. * scene.add( light );
  34490. * ```
  34491. *
  34492. * @augments Light
  34493. */
  34494. class AmbientLight extends Light {
  34495. /**
  34496. * Constructs a new ambient light.
  34497. *
  34498. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34499. * @param {number} [intensity=1] - The light's strength/intensity.
  34500. */
  34501. constructor( color, intensity ) {
  34502. super( color, intensity );
  34503. /**
  34504. * This flag can be used for type testing.
  34505. *
  34506. * @type {boolean}
  34507. * @readonly
  34508. * @default true
  34509. */
  34510. this.isAmbientLight = true;
  34511. this.type = 'AmbientLight';
  34512. }
  34513. }
  34514. /**
  34515. * This class emits light uniformly across the face a rectangular plane.
  34516. * This light type can be used to simulate light sources such as bright
  34517. * windows or strip lighting.
  34518. *
  34519. * Important Notes:
  34520. *
  34521. * - There is no shadow support.
  34522. * - Only PBR materials are supported.
  34523. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34524. * into your app and init the uniforms/textures.
  34525. *
  34526. * ```js
  34527. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34528. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34529. *
  34530. * const intensity = 1; const width = 10; const height = 10;
  34531. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34532. * rectLight.position.set( 5, 5, 0 );
  34533. * rectLight.lookAt( 0, 0, 0 );
  34534. * scene.add( rectLight )
  34535. * ```
  34536. *
  34537. * @augments Light
  34538. */
  34539. class RectAreaLight extends Light {
  34540. /**
  34541. * Constructs a new area light.
  34542. *
  34543. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34544. * @param {number} [intensity=1] - The light's strength/intensity.
  34545. * @param {number} [width=10] - The width of the light.
  34546. * @param {number} [height=10] - The height of the light.
  34547. */
  34548. constructor( color, intensity, width = 10, height = 10 ) {
  34549. super( color, intensity );
  34550. /**
  34551. * This flag can be used for type testing.
  34552. *
  34553. * @type {boolean}
  34554. * @readonly
  34555. * @default true
  34556. */
  34557. this.isRectAreaLight = true;
  34558. this.type = 'RectAreaLight';
  34559. /**
  34560. * The width of the light.
  34561. *
  34562. * @type {number}
  34563. * @default 10
  34564. */
  34565. this.width = width;
  34566. /**
  34567. * The height of the light.
  34568. *
  34569. * @type {number}
  34570. * @default 10
  34571. */
  34572. this.height = height;
  34573. }
  34574. /**
  34575. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34576. * Changing the power will also change the light's intensity.
  34577. *
  34578. * @type {number}
  34579. */
  34580. get power() {
  34581. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34582. return this.intensity * this.width * this.height * Math.PI;
  34583. }
  34584. set power( power ) {
  34585. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34586. this.intensity = power / ( this.width * this.height * Math.PI );
  34587. }
  34588. copy( source ) {
  34589. super.copy( source );
  34590. this.width = source.width;
  34591. this.height = source.height;
  34592. return this;
  34593. }
  34594. toJSON( meta ) {
  34595. const data = super.toJSON( meta );
  34596. data.object.width = this.width;
  34597. data.object.height = this.height;
  34598. return data;
  34599. }
  34600. }
  34601. /**
  34602. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34603. * to encode lighting information.
  34604. *
  34605. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34606. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34607. */
  34608. class SphericalHarmonics3 {
  34609. /**
  34610. * Constructs a new spherical harmonics.
  34611. */
  34612. constructor() {
  34613. /**
  34614. * This flag can be used for type testing.
  34615. *
  34616. * @type {boolean}
  34617. * @readonly
  34618. * @default true
  34619. */
  34620. this.isSphericalHarmonics3 = true;
  34621. /**
  34622. * An array holding the (9) SH coefficients.
  34623. *
  34624. * @type {Array<Vector3>}
  34625. */
  34626. this.coefficients = [];
  34627. for ( let i = 0; i < 9; i ++ ) {
  34628. this.coefficients.push( new Vector3() );
  34629. }
  34630. }
  34631. /**
  34632. * Sets the given SH coefficients to this instance by copying
  34633. * the values.
  34634. *
  34635. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34636. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34637. */
  34638. set( coefficients ) {
  34639. for ( let i = 0; i < 9; i ++ ) {
  34640. this.coefficients[ i ].copy( coefficients[ i ] );
  34641. }
  34642. return this;
  34643. }
  34644. /**
  34645. * Sets all SH coefficients to `0`.
  34646. *
  34647. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34648. */
  34649. zero() {
  34650. for ( let i = 0; i < 9; i ++ ) {
  34651. this.coefficients[ i ].set( 0, 0, 0 );
  34652. }
  34653. return this;
  34654. }
  34655. /**
  34656. * Returns the radiance in the direction of the given normal.
  34657. *
  34658. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34659. * @param {Vector3} target - The target vector that is used to store the method's result.
  34660. * @return {Vector3} The radiance.
  34661. */
  34662. getAt( normal, target ) {
  34663. // normal is assumed to be unit length
  34664. const x = normal.x, y = normal.y, z = normal.z;
  34665. const coeff = this.coefficients;
  34666. // band 0
  34667. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34668. // band 1
  34669. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34670. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34671. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34672. // band 2
  34673. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34674. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34675. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34676. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34677. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34678. return target;
  34679. }
  34680. /**
  34681. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34682. * direction of the given normal.
  34683. *
  34684. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34685. * @param {Vector3} target - The target vector that is used to store the method's result.
  34686. * @return {Vector3} The irradiance.
  34687. */
  34688. getIrradianceAt( normal, target ) {
  34689. // normal is assumed to be unit length
  34690. const x = normal.x, y = normal.y, z = normal.z;
  34691. const coeff = this.coefficients;
  34692. // band 0
  34693. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34694. // band 1
  34695. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34696. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34697. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34698. // band 2
  34699. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34700. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34701. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34702. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34703. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34704. return target;
  34705. }
  34706. /**
  34707. * Adds the given SH to this instance.
  34708. *
  34709. * @param {SphericalHarmonics3} sh - The SH to add.
  34710. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34711. */
  34712. add( sh ) {
  34713. for ( let i = 0; i < 9; i ++ ) {
  34714. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34715. }
  34716. return this;
  34717. }
  34718. /**
  34719. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34720. * {@link SphericalHarmonics3#scale} at once.
  34721. *
  34722. * @param {SphericalHarmonics3} sh - The SH to add.
  34723. * @param {number} s - The scale factor.
  34724. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34725. */
  34726. addScaledSH( sh, s ) {
  34727. for ( let i = 0; i < 9; i ++ ) {
  34728. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34729. }
  34730. return this;
  34731. }
  34732. /**
  34733. * Scales this SH by the given scale factor.
  34734. *
  34735. * @param {number} s - The scale factor.
  34736. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34737. */
  34738. scale( s ) {
  34739. for ( let i = 0; i < 9; i ++ ) {
  34740. this.coefficients[ i ].multiplyScalar( s );
  34741. }
  34742. return this;
  34743. }
  34744. /**
  34745. * Linear interpolates between the given SH and this instance by the given
  34746. * alpha factor.
  34747. *
  34748. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34749. * @param {number} alpha - The alpha factor.
  34750. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34751. */
  34752. lerp( sh, alpha ) {
  34753. for ( let i = 0; i < 9; i ++ ) {
  34754. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34755. }
  34756. return this;
  34757. }
  34758. /**
  34759. * Returns `true` if this spherical harmonics is equal with the given one.
  34760. *
  34761. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34762. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34763. */
  34764. equals( sh ) {
  34765. for ( let i = 0; i < 9; i ++ ) {
  34766. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34767. return false;
  34768. }
  34769. }
  34770. return true;
  34771. }
  34772. /**
  34773. * Copies the values of the given spherical harmonics to this instance.
  34774. *
  34775. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34776. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34777. */
  34778. copy( sh ) {
  34779. return this.set( sh.coefficients );
  34780. }
  34781. /**
  34782. * Returns a new spherical harmonics with copied values from this instance.
  34783. *
  34784. * @return {SphericalHarmonics3} A clone of this instance.
  34785. */
  34786. clone() {
  34787. return new this.constructor().copy( this );
  34788. }
  34789. /**
  34790. * Sets the SH coefficients of this instance from the given array.
  34791. *
  34792. * @param {Array<number>} array - An array holding the SH coefficients.
  34793. * @param {number} [offset=0] - The array offset where to start copying.
  34794. * @return {SphericalHarmonics3} A clone of this instance.
  34795. */
  34796. fromArray( array, offset = 0 ) {
  34797. const coefficients = this.coefficients;
  34798. for ( let i = 0; i < 9; i ++ ) {
  34799. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34800. }
  34801. return this;
  34802. }
  34803. /**
  34804. * Returns an array with the SH coefficients, or copies them into the provided
  34805. * array. The coefficients are represented as numbers.
  34806. *
  34807. * @param {Array<number>} [array=[]] - The target array.
  34808. * @param {number} [offset=0] - The array offset where to start copying.
  34809. * @return {Array<number>} An array with flat SH coefficients.
  34810. */
  34811. toArray( array = [], offset = 0 ) {
  34812. const coefficients = this.coefficients;
  34813. for ( let i = 0; i < 9; i ++ ) {
  34814. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34815. }
  34816. return array;
  34817. }
  34818. /**
  34819. * Computes the SH basis for the given normal vector.
  34820. *
  34821. * @param {Vector3} normal - The normal.
  34822. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34823. */
  34824. static getBasisAt( normal, shBasis ) {
  34825. // normal is assumed to be unit length
  34826. const x = normal.x, y = normal.y, z = normal.z;
  34827. // band 0
  34828. shBasis[ 0 ] = 0.282095;
  34829. // band 1
  34830. shBasis[ 1 ] = 0.488603 * y;
  34831. shBasis[ 2 ] = 0.488603 * z;
  34832. shBasis[ 3 ] = 0.488603 * x;
  34833. // band 2
  34834. shBasis[ 4 ] = 1.092548 * x * y;
  34835. shBasis[ 5 ] = 1.092548 * y * z;
  34836. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34837. shBasis[ 7 ] = 1.092548 * x * z;
  34838. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34839. }
  34840. }
  34841. /**
  34842. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34843. * classical light sources (e.g. directional, point or spot lights), light
  34844. * probes do not emit light. Instead they store information about light
  34845. * passing through 3D space. During rendering, the light that hits a 3D
  34846. * object is approximated by using the data from the light probe.
  34847. *
  34848. * Light probes are usually created from (radiance) environment maps. The
  34849. * class {@link LightProbeGenerator} can be used to create light probes from
  34850. * cube textures or render targets. However, light estimation data could also
  34851. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34852. * augmented reality content that reacts to real world lighting.
  34853. *
  34854. * The current probe implementation in three.js supports so-called diffuse
  34855. * light probes. This type of light probe is functionally equivalent to an
  34856. * irradiance environment map.
  34857. *
  34858. * @augments Light
  34859. */
  34860. class LightProbe extends Light {
  34861. /**
  34862. * Constructs a new light probe.
  34863. *
  34864. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34865. * @param {number} [intensity=1] - The light's strength/intensity.
  34866. */
  34867. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34868. super( undefined, intensity );
  34869. /**
  34870. * This flag can be used for type testing.
  34871. *
  34872. * @type {boolean}
  34873. * @readonly
  34874. * @default true
  34875. */
  34876. this.isLightProbe = true;
  34877. /**
  34878. * A light probe uses spherical harmonics to encode lighting information.
  34879. *
  34880. * @type {SphericalHarmonics3}
  34881. */
  34882. this.sh = sh;
  34883. }
  34884. copy( source ) {
  34885. super.copy( source );
  34886. this.sh.copy( source.sh );
  34887. return this;
  34888. }
  34889. toJSON( meta ) {
  34890. const data = super.toJSON( meta );
  34891. data.object.sh = this.sh.toArray();
  34892. return data;
  34893. }
  34894. }
  34895. /**
  34896. * Class for loading materials. The files are internally
  34897. * loaded via {@link FileLoader}.
  34898. *
  34899. * ```js
  34900. * const loader = new THREE.MaterialLoader();
  34901. * const material = await loader.loadAsync( 'material.json' );
  34902. * ```
  34903. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34904. *
  34905. * @augments Loader
  34906. */
  34907. class MaterialLoader extends Loader {
  34908. /**
  34909. * Constructs a new material loader.
  34910. *
  34911. * @param {LoadingManager} [manager] - The loading manager.
  34912. */
  34913. constructor( manager ) {
  34914. super( manager );
  34915. /**
  34916. * A dictionary holding textures used by the material.
  34917. *
  34918. * @type {Object<string,Texture>}
  34919. */
  34920. this.textures = {};
  34921. }
  34922. /**
  34923. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34924. *
  34925. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34926. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34927. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34928. * @param {onErrorCallback} onError - Executed when errors occur.
  34929. */
  34930. load( url, onLoad, onProgress, onError ) {
  34931. const scope = this;
  34932. const loader = new FileLoader( scope.manager );
  34933. loader.setPath( scope.path );
  34934. loader.setRequestHeader( scope.requestHeader );
  34935. loader.setWithCredentials( scope.withCredentials );
  34936. loader.load( url, function ( text ) {
  34937. try {
  34938. onLoad( scope.parse( JSON.parse( text ) ) );
  34939. } catch ( e ) {
  34940. if ( onError ) {
  34941. onError( e );
  34942. } else {
  34943. error( e );
  34944. }
  34945. scope.manager.itemError( url );
  34946. }
  34947. }, onProgress, onError );
  34948. }
  34949. /**
  34950. * Parses the given JSON object and returns a material.
  34951. *
  34952. * @param {Object} json - The serialized material.
  34953. * @return {Material} The parsed material.
  34954. */
  34955. parse( json ) {
  34956. const textures = this.textures;
  34957. function getTexture( name ) {
  34958. if ( textures[ name ] === undefined ) {
  34959. warn( 'MaterialLoader: Undefined texture', name );
  34960. }
  34961. return textures[ name ];
  34962. }
  34963. const material = this.createMaterialFromType( json.type );
  34964. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34965. if ( json.name !== undefined ) material.name = json.name;
  34966. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34967. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34968. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34969. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34970. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34971. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34972. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34973. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34974. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34975. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34976. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34977. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34978. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34979. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34980. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34981. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34982. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34983. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34984. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34985. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34986. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34987. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34988. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34989. if ( json.fog !== undefined ) material.fog = json.fog;
  34990. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34991. if ( json.blending !== undefined ) material.blending = json.blending;
  34992. if ( json.combine !== undefined ) material.combine = json.combine;
  34993. if ( json.side !== undefined ) material.side = json.side;
  34994. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34995. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34996. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34997. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34998. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34999. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  35000. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  35001. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  35002. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  35003. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  35004. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  35005. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  35006. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  35007. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  35008. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  35009. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  35010. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  35011. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  35012. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  35013. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  35014. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  35015. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  35016. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  35017. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  35018. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  35019. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  35020. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  35021. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  35022. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  35023. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  35024. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  35025. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  35026. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  35027. if ( json.scale !== undefined ) material.scale = json.scale;
  35028. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  35029. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  35030. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  35031. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  35032. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  35033. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  35034. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  35035. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  35036. if ( json.visible !== undefined ) material.visible = json.visible;
  35037. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  35038. if ( json.userData !== undefined ) material.userData = json.userData;
  35039. if ( json.vertexColors !== undefined ) {
  35040. if ( typeof json.vertexColors === 'number' ) {
  35041. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  35042. } else {
  35043. material.vertexColors = json.vertexColors;
  35044. }
  35045. }
  35046. // Shader Material
  35047. if ( json.uniforms !== undefined ) {
  35048. for ( const name in json.uniforms ) {
  35049. const uniform = json.uniforms[ name ];
  35050. material.uniforms[ name ] = {};
  35051. switch ( uniform.type ) {
  35052. case 't':
  35053. material.uniforms[ name ].value = getTexture( uniform.value );
  35054. break;
  35055. case 'c':
  35056. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  35057. break;
  35058. case 'v2':
  35059. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  35060. break;
  35061. case 'v3':
  35062. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  35063. break;
  35064. case 'v4':
  35065. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  35066. break;
  35067. case 'm3':
  35068. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  35069. break;
  35070. case 'm4':
  35071. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  35072. break;
  35073. default:
  35074. material.uniforms[ name ].value = uniform.value;
  35075. }
  35076. }
  35077. }
  35078. if ( json.defines !== undefined ) material.defines = json.defines;
  35079. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  35080. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  35081. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  35082. if ( json.extensions !== undefined ) {
  35083. for ( const key in json.extensions ) {
  35084. material.extensions[ key ] = json.extensions[ key ];
  35085. }
  35086. }
  35087. if ( json.lights !== undefined ) material.lights = json.lights;
  35088. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  35089. // for PointsMaterial
  35090. if ( json.size !== undefined ) material.size = json.size;
  35091. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  35092. // maps
  35093. if ( json.map !== undefined ) material.map = getTexture( json.map );
  35094. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  35095. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  35096. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  35097. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  35098. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  35099. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  35100. if ( json.normalScale !== undefined ) {
  35101. let normalScale = json.normalScale;
  35102. if ( Array.isArray( normalScale ) === false ) {
  35103. // Blender exporter used to export a scalar. See #7459
  35104. normalScale = [ normalScale, normalScale ];
  35105. }
  35106. material.normalScale = new Vector2().fromArray( normalScale );
  35107. }
  35108. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  35109. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  35110. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  35111. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  35112. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  35113. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  35114. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  35115. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  35116. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  35117. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  35118. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  35119. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  35120. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  35121. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  35122. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  35123. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  35124. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  35125. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  35126. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  35127. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  35128. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  35129. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  35130. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  35131. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  35132. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  35133. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  35134. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  35135. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  35136. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  35137. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  35138. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  35139. return material;
  35140. }
  35141. /**
  35142. * Textures are not embedded in the material JSON so they have
  35143. * to be injected before the loading process starts.
  35144. *
  35145. * @param {Object} value - A dictionary holding textures for material properties.
  35146. * @return {MaterialLoader} A reference to this material loader.
  35147. */
  35148. setTextures( value ) {
  35149. this.textures = value;
  35150. return this;
  35151. }
  35152. /**
  35153. * Creates a material for the given type.
  35154. *
  35155. * @param {string} type - The material type.
  35156. * @return {Material} The new material.
  35157. */
  35158. createMaterialFromType( type ) {
  35159. return MaterialLoader.createMaterialFromType( type );
  35160. }
  35161. /**
  35162. * Creates a material for the given type.
  35163. *
  35164. * @static
  35165. * @param {string} type - The material type.
  35166. * @return {Material} The new material.
  35167. */
  35168. static createMaterialFromType( type ) {
  35169. const materialLib = {
  35170. ShadowMaterial,
  35171. SpriteMaterial,
  35172. RawShaderMaterial,
  35173. ShaderMaterial,
  35174. PointsMaterial,
  35175. MeshPhysicalMaterial,
  35176. MeshStandardMaterial,
  35177. MeshPhongMaterial,
  35178. MeshToonMaterial,
  35179. MeshNormalMaterial,
  35180. MeshLambertMaterial,
  35181. MeshDepthMaterial,
  35182. MeshDistanceMaterial,
  35183. MeshBasicMaterial,
  35184. MeshMatcapMaterial,
  35185. LineDashedMaterial,
  35186. LineBasicMaterial,
  35187. Material
  35188. };
  35189. return new materialLib[ type ]();
  35190. }
  35191. }
  35192. /**
  35193. * A class with loader utility functions.
  35194. */
  35195. class LoaderUtils {
  35196. /**
  35197. * Extracts the base URL from the given URL.
  35198. *
  35199. * @param {string} url -The URL to extract the base URL from.
  35200. * @return {string} The extracted base URL.
  35201. */
  35202. static extractUrlBase( url ) {
  35203. const index = url.lastIndexOf( '/' );
  35204. if ( index === -1 ) return './';
  35205. return url.slice( 0, index + 1 );
  35206. }
  35207. /**
  35208. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35209. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35210. * string.
  35211. *
  35212. * @param {string} url -The URL to resolve.
  35213. * @param {string} path - The base path for relative URLs to be resolved against.
  35214. * @return {string} The resolved URL.
  35215. */
  35216. static resolveURL( url, path ) {
  35217. // Invalid URL
  35218. if ( typeof url !== 'string' || url === '' ) return '';
  35219. // Host Relative URL
  35220. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35221. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35222. }
  35223. // Absolute URL http://,https://,//
  35224. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35225. // Data URI
  35226. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35227. // Blob URL
  35228. if ( /^blob:.*$/i.test( url ) ) return url;
  35229. // Relative URL
  35230. return path + url;
  35231. }
  35232. }
  35233. /**
  35234. * An instanced version of a geometry.
  35235. */
  35236. class InstancedBufferGeometry extends BufferGeometry {
  35237. /**
  35238. * Constructs a new instanced buffer geometry.
  35239. */
  35240. constructor() {
  35241. super();
  35242. /**
  35243. * This flag can be used for type testing.
  35244. *
  35245. * @type {boolean}
  35246. * @readonly
  35247. * @default true
  35248. */
  35249. this.isInstancedBufferGeometry = true;
  35250. this.type = 'InstancedBufferGeometry';
  35251. /**
  35252. * The instance count.
  35253. *
  35254. * @type {number}
  35255. * @default Infinity
  35256. */
  35257. this.instanceCount = Infinity;
  35258. }
  35259. copy( source ) {
  35260. super.copy( source );
  35261. this.instanceCount = source.instanceCount;
  35262. return this;
  35263. }
  35264. toJSON() {
  35265. const data = super.toJSON();
  35266. data.instanceCount = this.instanceCount;
  35267. data.isInstancedBufferGeometry = true;
  35268. return data;
  35269. }
  35270. }
  35271. /**
  35272. * Class for loading geometries. The files are internally
  35273. * loaded via {@link FileLoader}.
  35274. *
  35275. * ```js
  35276. * const loader = new THREE.BufferGeometryLoader();
  35277. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35278. *
  35279. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35280. * const object = new THREE.Mesh( geometry, material );
  35281. * scene.add( object );
  35282. * ```
  35283. *
  35284. * @augments Loader
  35285. */
  35286. class BufferGeometryLoader extends Loader {
  35287. /**
  35288. * Constructs a new geometry loader.
  35289. *
  35290. * @param {LoadingManager} [manager] - The loading manager.
  35291. */
  35292. constructor( manager ) {
  35293. super( manager );
  35294. }
  35295. /**
  35296. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35297. *
  35298. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35299. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35300. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35301. * @param {onErrorCallback} onError - Executed when errors occur.
  35302. */
  35303. load( url, onLoad, onProgress, onError ) {
  35304. const scope = this;
  35305. const loader = new FileLoader( scope.manager );
  35306. loader.setPath( scope.path );
  35307. loader.setRequestHeader( scope.requestHeader );
  35308. loader.setWithCredentials( scope.withCredentials );
  35309. loader.load( url, function ( text ) {
  35310. try {
  35311. onLoad( scope.parse( JSON.parse( text ) ) );
  35312. } catch ( e ) {
  35313. if ( onError ) {
  35314. onError( e );
  35315. } else {
  35316. error( e );
  35317. }
  35318. scope.manager.itemError( url );
  35319. }
  35320. }, onProgress, onError );
  35321. }
  35322. /**
  35323. * Parses the given JSON object and returns a geometry.
  35324. *
  35325. * @param {Object} json - The serialized geometry.
  35326. * @return {BufferGeometry} The parsed geometry.
  35327. */
  35328. parse( json ) {
  35329. const interleavedBufferMap = {};
  35330. const arrayBufferMap = {};
  35331. function getInterleavedBuffer( json, uuid ) {
  35332. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35333. const interleavedBuffers = json.interleavedBuffers;
  35334. const interleavedBuffer = interleavedBuffers[ uuid ];
  35335. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35336. const array = getTypedArray( interleavedBuffer.type, buffer );
  35337. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35338. ib.uuid = interleavedBuffer.uuid;
  35339. interleavedBufferMap[ uuid ] = ib;
  35340. return ib;
  35341. }
  35342. function getArrayBuffer( json, uuid ) {
  35343. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35344. const arrayBuffers = json.arrayBuffers;
  35345. const arrayBuffer = arrayBuffers[ uuid ];
  35346. const ab = new Uint32Array( arrayBuffer ).buffer;
  35347. arrayBufferMap[ uuid ] = ab;
  35348. return ab;
  35349. }
  35350. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35351. const index = json.data.index;
  35352. if ( index !== undefined ) {
  35353. const typedArray = getTypedArray( index.type, index.array );
  35354. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35355. }
  35356. const attributes = json.data.attributes;
  35357. for ( const key in attributes ) {
  35358. const attribute = attributes[ key ];
  35359. let bufferAttribute;
  35360. if ( attribute.isInterleavedBufferAttribute ) {
  35361. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35362. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35363. } else {
  35364. const typedArray = getTypedArray( attribute.type, attribute.array );
  35365. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35366. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35367. }
  35368. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35369. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35370. geometry.setAttribute( key, bufferAttribute );
  35371. }
  35372. const morphAttributes = json.data.morphAttributes;
  35373. if ( morphAttributes ) {
  35374. for ( const key in morphAttributes ) {
  35375. const attributeArray = morphAttributes[ key ];
  35376. const array = [];
  35377. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35378. const attribute = attributeArray[ i ];
  35379. let bufferAttribute;
  35380. if ( attribute.isInterleavedBufferAttribute ) {
  35381. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35382. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35383. } else {
  35384. const typedArray = getTypedArray( attribute.type, attribute.array );
  35385. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35386. }
  35387. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35388. array.push( bufferAttribute );
  35389. }
  35390. geometry.morphAttributes[ key ] = array;
  35391. }
  35392. }
  35393. const morphTargetsRelative = json.data.morphTargetsRelative;
  35394. if ( morphTargetsRelative ) {
  35395. geometry.morphTargetsRelative = true;
  35396. }
  35397. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35398. if ( groups !== undefined ) {
  35399. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35400. const group = groups[ i ];
  35401. geometry.addGroup( group.start, group.count, group.materialIndex );
  35402. }
  35403. }
  35404. const boundingSphere = json.data.boundingSphere;
  35405. if ( boundingSphere !== undefined ) {
  35406. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35407. }
  35408. if ( json.name ) geometry.name = json.name;
  35409. if ( json.userData ) geometry.userData = json.userData;
  35410. return geometry;
  35411. }
  35412. }
  35413. /**
  35414. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  35415. * The files are internally loaded via {@link FileLoader}.
  35416. *
  35417. * ```js
  35418. * const loader = new THREE.ObjectLoader();
  35419. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35420. * scene.add( obj );
  35421. *
  35422. * // Alternatively, to parse a previously loaded JSON structure
  35423. * const object = await loader.parseAsync( a_json_object );
  35424. * scene.add( object );
  35425. * ```
  35426. *
  35427. * @augments Loader
  35428. */
  35429. class ObjectLoader extends Loader {
  35430. /**
  35431. * Constructs a new object loader.
  35432. *
  35433. * @param {LoadingManager} [manager] - The loading manager.
  35434. */
  35435. constructor( manager ) {
  35436. super( manager );
  35437. }
  35438. /**
  35439. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35440. *
  35441. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35442. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35443. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35444. * @param {onErrorCallback} onError - Executed when errors occur.
  35445. */
  35446. load( url, onLoad, onProgress, onError ) {
  35447. const scope = this;
  35448. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35449. this.resourcePath = this.resourcePath || path;
  35450. const loader = new FileLoader( this.manager );
  35451. loader.setPath( this.path );
  35452. loader.setRequestHeader( this.requestHeader );
  35453. loader.setWithCredentials( this.withCredentials );
  35454. loader.load( url, function ( text ) {
  35455. let json = null;
  35456. try {
  35457. json = JSON.parse( text );
  35458. } catch ( error ) {
  35459. if ( onError !== undefined ) onError( error );
  35460. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35461. return;
  35462. }
  35463. const metadata = json.metadata;
  35464. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35465. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35466. error( 'ObjectLoader: Can\'t load ' + url );
  35467. return;
  35468. }
  35469. scope.parse( json, onLoad );
  35470. }, onProgress, onError );
  35471. }
  35472. /**
  35473. * Async version of {@link ObjectLoader#load}.
  35474. *
  35475. * @async
  35476. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35477. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35478. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35479. */
  35480. async loadAsync( url, onProgress ) {
  35481. const scope = this;
  35482. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35483. this.resourcePath = this.resourcePath || path;
  35484. const loader = new FileLoader( this.manager );
  35485. loader.setPath( this.path );
  35486. loader.setRequestHeader( this.requestHeader );
  35487. loader.setWithCredentials( this.withCredentials );
  35488. const text = await loader.loadAsync( url, onProgress );
  35489. const json = JSON.parse( text );
  35490. const metadata = json.metadata;
  35491. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35492. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35493. }
  35494. return await scope.parseAsync( json );
  35495. }
  35496. /**
  35497. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35498. * but can also be used directly to parse a previously loaded JSON structure.
  35499. *
  35500. * @param {Object} json - The serialized 3D object.
  35501. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35502. * @return {Object3D} The parsed 3D object.
  35503. */
  35504. parse( json, onLoad ) {
  35505. const animations = this.parseAnimations( json.animations );
  35506. const shapes = this.parseShapes( json.shapes );
  35507. const geometries = this.parseGeometries( json.geometries, shapes );
  35508. const images = this.parseImages( json.images, function () {
  35509. if ( onLoad !== undefined ) onLoad( object );
  35510. } );
  35511. const textures = this.parseTextures( json.textures, images );
  35512. const materials = this.parseMaterials( json.materials, textures );
  35513. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35514. const skeletons = this.parseSkeletons( json.skeletons, object );
  35515. this.bindSkeletons( object, skeletons );
  35516. this.bindLightTargets( object );
  35517. //
  35518. if ( onLoad !== undefined ) {
  35519. let hasImages = false;
  35520. for ( const uuid in images ) {
  35521. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35522. hasImages = true;
  35523. break;
  35524. }
  35525. }
  35526. if ( hasImages === false ) onLoad( object );
  35527. }
  35528. return object;
  35529. }
  35530. /**
  35531. * Async version of {@link ObjectLoader#parse}.
  35532. *
  35533. * @param {Object} json - The serialized 3D object.
  35534. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35535. */
  35536. async parseAsync( json ) {
  35537. const animations = this.parseAnimations( json.animations );
  35538. const shapes = this.parseShapes( json.shapes );
  35539. const geometries = this.parseGeometries( json.geometries, shapes );
  35540. const images = await this.parseImagesAsync( json.images );
  35541. const textures = this.parseTextures( json.textures, images );
  35542. const materials = this.parseMaterials( json.materials, textures );
  35543. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35544. const skeletons = this.parseSkeletons( json.skeletons, object );
  35545. this.bindSkeletons( object, skeletons );
  35546. this.bindLightTargets( object );
  35547. return object;
  35548. }
  35549. // internals
  35550. parseShapes( json ) {
  35551. const shapes = {};
  35552. if ( json !== undefined ) {
  35553. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35554. const shape = new Shape().fromJSON( json[ i ] );
  35555. shapes[ shape.uuid ] = shape;
  35556. }
  35557. }
  35558. return shapes;
  35559. }
  35560. parseSkeletons( json, object ) {
  35561. const skeletons = {};
  35562. const bones = {};
  35563. // generate bone lookup table
  35564. object.traverse( function ( child ) {
  35565. if ( child.isBone ) bones[ child.uuid ] = child;
  35566. } );
  35567. // create skeletons
  35568. if ( json !== undefined ) {
  35569. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35570. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35571. skeletons[ skeleton.uuid ] = skeleton;
  35572. }
  35573. }
  35574. return skeletons;
  35575. }
  35576. parseGeometries( json, shapes ) {
  35577. const geometries = {};
  35578. if ( json !== undefined ) {
  35579. const bufferGeometryLoader = new BufferGeometryLoader();
  35580. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35581. let geometry;
  35582. const data = json[ i ];
  35583. switch ( data.type ) {
  35584. case 'BufferGeometry':
  35585. case 'InstancedBufferGeometry':
  35586. geometry = bufferGeometryLoader.parse( data );
  35587. break;
  35588. default:
  35589. if ( data.type in Geometries ) {
  35590. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35591. } else {
  35592. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35593. }
  35594. }
  35595. geometry.uuid = data.uuid;
  35596. if ( data.name !== undefined ) geometry.name = data.name;
  35597. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35598. geometries[ data.uuid ] = geometry;
  35599. }
  35600. }
  35601. return geometries;
  35602. }
  35603. parseMaterials( json, textures ) {
  35604. const cache = {}; // MultiMaterial
  35605. const materials = {};
  35606. if ( json !== undefined ) {
  35607. const loader = new MaterialLoader();
  35608. loader.setTextures( textures );
  35609. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35610. const data = json[ i ];
  35611. if ( cache[ data.uuid ] === undefined ) {
  35612. cache[ data.uuid ] = loader.parse( data );
  35613. }
  35614. materials[ data.uuid ] = cache[ data.uuid ];
  35615. }
  35616. }
  35617. return materials;
  35618. }
  35619. parseAnimations( json ) {
  35620. const animations = {};
  35621. if ( json !== undefined ) {
  35622. for ( let i = 0; i < json.length; i ++ ) {
  35623. const data = json[ i ];
  35624. const clip = AnimationClip.parse( data );
  35625. animations[ clip.uuid ] = clip;
  35626. }
  35627. }
  35628. return animations;
  35629. }
  35630. parseImages( json, onLoad ) {
  35631. const scope = this;
  35632. const images = {};
  35633. let loader;
  35634. function loadImage( url ) {
  35635. scope.manager.itemStart( url );
  35636. return loader.load( url, function () {
  35637. scope.manager.itemEnd( url );
  35638. }, undefined, function () {
  35639. scope.manager.itemError( url );
  35640. scope.manager.itemEnd( url );
  35641. } );
  35642. }
  35643. function deserializeImage( image ) {
  35644. if ( typeof image === 'string' ) {
  35645. const url = image;
  35646. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35647. return loadImage( path );
  35648. } else {
  35649. if ( image.data ) {
  35650. return {
  35651. data: getTypedArray( image.type, image.data ),
  35652. width: image.width,
  35653. height: image.height
  35654. };
  35655. } else {
  35656. return null;
  35657. }
  35658. }
  35659. }
  35660. if ( json !== undefined && json.length > 0 ) {
  35661. const manager = new LoadingManager( onLoad );
  35662. loader = new ImageLoader( manager );
  35663. loader.setCrossOrigin( this.crossOrigin );
  35664. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35665. const image = json[ i ];
  35666. const url = image.url;
  35667. if ( Array.isArray( url ) ) {
  35668. // load array of images e.g CubeTexture
  35669. const imageArray = [];
  35670. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35671. const currentUrl = url[ j ];
  35672. const deserializedImage = deserializeImage( currentUrl );
  35673. if ( deserializedImage !== null ) {
  35674. if ( deserializedImage instanceof HTMLImageElement ) {
  35675. imageArray.push( deserializedImage );
  35676. } else {
  35677. // special case: handle array of data textures for cube textures
  35678. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35679. }
  35680. }
  35681. }
  35682. images[ image.uuid ] = new Source( imageArray );
  35683. } else {
  35684. // load single image
  35685. const deserializedImage = deserializeImage( image.url );
  35686. images[ image.uuid ] = new Source( deserializedImage );
  35687. }
  35688. }
  35689. }
  35690. return images;
  35691. }
  35692. async parseImagesAsync( json ) {
  35693. const scope = this;
  35694. const images = {};
  35695. let loader;
  35696. async function deserializeImage( image ) {
  35697. if ( typeof image === 'string' ) {
  35698. const url = image;
  35699. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35700. return await loader.loadAsync( path );
  35701. } else {
  35702. if ( image.data ) {
  35703. return {
  35704. data: getTypedArray( image.type, image.data ),
  35705. width: image.width,
  35706. height: image.height
  35707. };
  35708. } else {
  35709. return null;
  35710. }
  35711. }
  35712. }
  35713. if ( json !== undefined && json.length > 0 ) {
  35714. loader = new ImageLoader( this.manager );
  35715. loader.setCrossOrigin( this.crossOrigin );
  35716. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35717. const image = json[ i ];
  35718. const url = image.url;
  35719. if ( Array.isArray( url ) ) {
  35720. // load array of images e.g CubeTexture
  35721. const imageArray = [];
  35722. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35723. const currentUrl = url[ j ];
  35724. const deserializedImage = await deserializeImage( currentUrl );
  35725. if ( deserializedImage !== null ) {
  35726. if ( deserializedImage instanceof HTMLImageElement ) {
  35727. imageArray.push( deserializedImage );
  35728. } else {
  35729. // special case: handle array of data textures for cube textures
  35730. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35731. }
  35732. }
  35733. }
  35734. images[ image.uuid ] = new Source( imageArray );
  35735. } else {
  35736. // load single image
  35737. const deserializedImage = await deserializeImage( image.url );
  35738. images[ image.uuid ] = new Source( deserializedImage );
  35739. }
  35740. }
  35741. }
  35742. return images;
  35743. }
  35744. parseTextures( json, images ) {
  35745. function parseConstant( value, type ) {
  35746. if ( typeof value === 'number' ) return value;
  35747. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35748. return type[ value ];
  35749. }
  35750. const textures = {};
  35751. if ( json !== undefined ) {
  35752. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35753. const data = json[ i ];
  35754. if ( data.image === undefined ) {
  35755. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35756. }
  35757. if ( images[ data.image ] === undefined ) {
  35758. warn( 'ObjectLoader: Undefined image', data.image );
  35759. }
  35760. const source = images[ data.image ];
  35761. const image = source.data;
  35762. let texture;
  35763. if ( Array.isArray( image ) ) {
  35764. texture = new CubeTexture();
  35765. if ( image.length === 6 ) texture.needsUpdate = true;
  35766. } else {
  35767. if ( image && image.data ) {
  35768. texture = new DataTexture();
  35769. } else {
  35770. texture = new Texture();
  35771. }
  35772. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35773. }
  35774. texture.source = source;
  35775. texture.uuid = data.uuid;
  35776. if ( data.name !== undefined ) texture.name = data.name;
  35777. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35778. if ( data.channel !== undefined ) texture.channel = data.channel;
  35779. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35780. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35781. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35782. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35783. if ( data.wrap !== undefined ) {
  35784. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35785. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35786. }
  35787. if ( data.format !== undefined ) texture.format = data.format;
  35788. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35789. if ( data.type !== undefined ) texture.type = data.type;
  35790. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35791. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35792. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35793. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35794. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35795. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35796. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35797. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35798. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35799. if ( data.userData !== undefined ) texture.userData = data.userData;
  35800. textures[ data.uuid ] = texture;
  35801. }
  35802. }
  35803. return textures;
  35804. }
  35805. parseObject( data, geometries, materials, textures, animations ) {
  35806. let object;
  35807. function getGeometry( name ) {
  35808. if ( geometries[ name ] === undefined ) {
  35809. warn( 'ObjectLoader: Undefined geometry', name );
  35810. }
  35811. return geometries[ name ];
  35812. }
  35813. function getMaterial( name ) {
  35814. if ( name === undefined ) return undefined;
  35815. if ( Array.isArray( name ) ) {
  35816. const array = [];
  35817. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35818. const uuid = name[ i ];
  35819. if ( materials[ uuid ] === undefined ) {
  35820. warn( 'ObjectLoader: Undefined material', uuid );
  35821. }
  35822. array.push( materials[ uuid ] );
  35823. }
  35824. return array;
  35825. }
  35826. if ( materials[ name ] === undefined ) {
  35827. warn( 'ObjectLoader: Undefined material', name );
  35828. }
  35829. return materials[ name ];
  35830. }
  35831. function getTexture( uuid ) {
  35832. if ( textures[ uuid ] === undefined ) {
  35833. warn( 'ObjectLoader: Undefined texture', uuid );
  35834. }
  35835. return textures[ uuid ];
  35836. }
  35837. let geometry, material;
  35838. switch ( data.type ) {
  35839. case 'Scene':
  35840. object = new Scene();
  35841. if ( data.background !== undefined ) {
  35842. if ( Number.isInteger( data.background ) ) {
  35843. object.background = new Color( data.background );
  35844. } else {
  35845. object.background = getTexture( data.background );
  35846. }
  35847. }
  35848. if ( data.environment !== undefined ) {
  35849. object.environment = getTexture( data.environment );
  35850. }
  35851. if ( data.fog !== undefined ) {
  35852. if ( data.fog.type === 'Fog' ) {
  35853. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35854. } else if ( data.fog.type === 'FogExp2' ) {
  35855. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35856. }
  35857. if ( data.fog.name !== '' ) {
  35858. object.fog.name = data.fog.name;
  35859. }
  35860. }
  35861. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35862. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35863. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35864. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35865. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35866. break;
  35867. case 'PerspectiveCamera':
  35868. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35869. if ( data.focus !== undefined ) object.focus = data.focus;
  35870. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35871. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35872. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35873. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35874. break;
  35875. case 'OrthographicCamera':
  35876. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35877. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35878. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35879. break;
  35880. case 'AmbientLight':
  35881. object = new AmbientLight( data.color, data.intensity );
  35882. break;
  35883. case 'DirectionalLight':
  35884. object = new DirectionalLight( data.color, data.intensity );
  35885. object.target = data.target || '';
  35886. break;
  35887. case 'PointLight':
  35888. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35889. break;
  35890. case 'RectAreaLight':
  35891. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35892. break;
  35893. case 'SpotLight':
  35894. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35895. object.target = data.target || '';
  35896. break;
  35897. case 'HemisphereLight':
  35898. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35899. break;
  35900. case 'LightProbe':
  35901. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35902. object = new LightProbe( sh, data.intensity );
  35903. break;
  35904. case 'SkinnedMesh':
  35905. geometry = getGeometry( data.geometry );
  35906. material = getMaterial( data.material );
  35907. object = new SkinnedMesh( geometry, material );
  35908. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35909. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35910. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35911. break;
  35912. case 'Mesh':
  35913. geometry = getGeometry( data.geometry );
  35914. material = getMaterial( data.material );
  35915. object = new Mesh( geometry, material );
  35916. break;
  35917. case 'InstancedMesh':
  35918. geometry = getGeometry( data.geometry );
  35919. material = getMaterial( data.material );
  35920. const count = data.count;
  35921. const instanceMatrix = data.instanceMatrix;
  35922. const instanceColor = data.instanceColor;
  35923. object = new InstancedMesh( geometry, material, count );
  35924. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35925. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35926. break;
  35927. case 'BatchedMesh':
  35928. geometry = getGeometry( data.geometry );
  35929. material = getMaterial( data.material );
  35930. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35931. object.geometry = geometry;
  35932. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35933. object.sortObjects = data.sortObjects;
  35934. object._drawRanges = data.drawRanges;
  35935. object._reservedRanges = data.reservedRanges;
  35936. object._geometryInfo = data.geometryInfo.map( info => {
  35937. let box = null;
  35938. let sphere = null;
  35939. if ( info.boundingBox !== undefined ) {
  35940. box = new Box3().fromJSON( info.boundingBox );
  35941. }
  35942. if ( info.boundingSphere !== undefined ) {
  35943. sphere = new Sphere().fromJSON( info.boundingSphere );
  35944. }
  35945. return {
  35946. ...info,
  35947. boundingBox: box,
  35948. boundingSphere: sphere
  35949. };
  35950. } );
  35951. object._instanceInfo = data.instanceInfo;
  35952. object._availableInstanceIds = data._availableInstanceIds;
  35953. object._availableGeometryIds = data._availableGeometryIds;
  35954. object._nextIndexStart = data.nextIndexStart;
  35955. object._nextVertexStart = data.nextVertexStart;
  35956. object._geometryCount = data.geometryCount;
  35957. object._maxInstanceCount = data.maxInstanceCount;
  35958. object._maxVertexCount = data.maxVertexCount;
  35959. object._maxIndexCount = data.maxIndexCount;
  35960. object._geometryInitialized = data.geometryInitialized;
  35961. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35962. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35963. if ( data.colorsTexture !== undefined ) {
  35964. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35965. }
  35966. if ( data.boundingSphere !== undefined ) {
  35967. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35968. }
  35969. if ( data.boundingBox !== undefined ) {
  35970. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35971. }
  35972. break;
  35973. case 'LOD':
  35974. object = new LOD();
  35975. break;
  35976. case 'Line':
  35977. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35978. break;
  35979. case 'LineLoop':
  35980. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35981. break;
  35982. case 'LineSegments':
  35983. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35984. break;
  35985. case 'PointCloud':
  35986. case 'Points':
  35987. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35988. break;
  35989. case 'Sprite':
  35990. object = new Sprite( getMaterial( data.material ) );
  35991. break;
  35992. case 'Group':
  35993. object = new Group();
  35994. break;
  35995. case 'Bone':
  35996. object = new Bone();
  35997. break;
  35998. default:
  35999. object = new Object3D();
  36000. }
  36001. object.uuid = data.uuid;
  36002. if ( data.name !== undefined ) object.name = data.name;
  36003. if ( data.matrix !== undefined ) {
  36004. object.matrix.fromArray( data.matrix );
  36005. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  36006. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  36007. } else {
  36008. if ( data.position !== undefined ) object.position.fromArray( data.position );
  36009. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  36010. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  36011. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  36012. }
  36013. if ( data.up !== undefined ) object.up.fromArray( data.up );
  36014. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  36015. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  36016. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  36017. if ( data.shadow ) {
  36018. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  36019. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  36020. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  36021. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  36022. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  36023. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  36024. }
  36025. if ( data.visible !== undefined ) object.visible = data.visible;
  36026. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  36027. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  36028. if ( data.static !== undefined ) object.static = data.static;
  36029. if ( data.userData !== undefined ) object.userData = data.userData;
  36030. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  36031. if ( data.children !== undefined ) {
  36032. const children = data.children;
  36033. for ( let i = 0; i < children.length; i ++ ) {
  36034. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  36035. }
  36036. }
  36037. if ( data.animations !== undefined ) {
  36038. const objectAnimations = data.animations;
  36039. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  36040. const uuid = objectAnimations[ i ];
  36041. object.animations.push( animations[ uuid ] );
  36042. }
  36043. }
  36044. if ( data.type === 'LOD' ) {
  36045. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  36046. const levels = data.levels;
  36047. for ( let l = 0; l < levels.length; l ++ ) {
  36048. const level = levels[ l ];
  36049. const child = object.getObjectByProperty( 'uuid', level.object );
  36050. if ( child !== undefined ) {
  36051. object.addLevel( child, level.distance, level.hysteresis );
  36052. }
  36053. }
  36054. }
  36055. return object;
  36056. }
  36057. bindSkeletons( object, skeletons ) {
  36058. if ( Object.keys( skeletons ).length === 0 ) return;
  36059. object.traverse( function ( child ) {
  36060. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  36061. const skeleton = skeletons[ child.skeleton ];
  36062. if ( skeleton === undefined ) {
  36063. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  36064. } else {
  36065. child.bind( skeleton, child.bindMatrix );
  36066. }
  36067. }
  36068. } );
  36069. }
  36070. bindLightTargets( object ) {
  36071. object.traverse( function ( child ) {
  36072. if ( child.isDirectionalLight || child.isSpotLight ) {
  36073. const uuid = child.target;
  36074. const target = object.getObjectByProperty( 'uuid', uuid );
  36075. if ( target !== undefined ) {
  36076. child.target = target;
  36077. } else {
  36078. child.target = new Object3D();
  36079. }
  36080. }
  36081. } );
  36082. }
  36083. }
  36084. const TEXTURE_MAPPING = {
  36085. UVMapping: UVMapping,
  36086. CubeReflectionMapping: CubeReflectionMapping,
  36087. CubeRefractionMapping: CubeRefractionMapping,
  36088. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  36089. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  36090. CubeUVReflectionMapping: CubeUVReflectionMapping
  36091. };
  36092. const TEXTURE_WRAPPING = {
  36093. RepeatWrapping: RepeatWrapping,
  36094. ClampToEdgeWrapping: ClampToEdgeWrapping,
  36095. MirroredRepeatWrapping: MirroredRepeatWrapping
  36096. };
  36097. const TEXTURE_FILTER = {
  36098. NearestFilter: NearestFilter,
  36099. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  36100. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  36101. LinearFilter: LinearFilter,
  36102. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  36103. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  36104. };
  36105. const _errorMap = new WeakMap();
  36106. /**
  36107. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  36108. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  36109. * textures for rendering.
  36110. *
  36111. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  36112. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  36113. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  36114. *
  36115. * To match the default behaviour of {@link Texture}, the following options are needed:
  36116. *
  36117. * ```js
  36118. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  36119. * ```
  36120. *
  36121. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  36122. *
  36123. * ```js
  36124. * const loader = new THREE.ImageBitmapLoader();
  36125. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  36126. * const imageBitmap = await loader.loadAsync( 'image.png' );
  36127. *
  36128. * const texture = new THREE.Texture( imageBitmap );
  36129. * texture.needsUpdate = true;
  36130. * ```
  36131. *
  36132. * @augments Loader
  36133. */
  36134. class ImageBitmapLoader extends Loader {
  36135. /**
  36136. * Constructs a new image bitmap loader.
  36137. *
  36138. * @param {LoadingManager} [manager] - The loading manager.
  36139. */
  36140. constructor( manager ) {
  36141. super( manager );
  36142. /**
  36143. * This flag can be used for type testing.
  36144. *
  36145. * @type {boolean}
  36146. * @readonly
  36147. * @default true
  36148. */
  36149. this.isImageBitmapLoader = true;
  36150. if ( typeof createImageBitmap === 'undefined' ) {
  36151. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36152. }
  36153. if ( typeof fetch === 'undefined' ) {
  36154. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36155. }
  36156. /**
  36157. * Represents the loader options.
  36158. *
  36159. * @type {Object}
  36160. * @default {premultiplyAlpha:'none'}
  36161. */
  36162. this.options = { premultiplyAlpha: 'none' };
  36163. /**
  36164. * Used for aborting requests.
  36165. *
  36166. * @private
  36167. * @type {AbortController}
  36168. */
  36169. this._abortController = new AbortController();
  36170. }
  36171. /**
  36172. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36173. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36174. *
  36175. * @param {Object} options - The loader options to set.
  36176. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36177. */
  36178. setOptions( options ) {
  36179. this.options = options;
  36180. return this;
  36181. }
  36182. /**
  36183. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36184. *
  36185. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36186. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36187. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36188. * @param {onErrorCallback} onError - Executed when errors occur.
  36189. * @return {ImageBitmap|undefined} The image bitmap.
  36190. */
  36191. load( url, onLoad, onProgress, onError ) {
  36192. if ( url === undefined ) url = '';
  36193. if ( this.path !== undefined ) url = this.path + url;
  36194. url = this.manager.resolveURL( url );
  36195. const scope = this;
  36196. const cached = Cache.get( `image-bitmap:${url}` );
  36197. if ( cached !== undefined ) {
  36198. scope.manager.itemStart( url );
  36199. // If cached is a promise, wait for it to resolve
  36200. if ( cached.then ) {
  36201. cached.then( imageBitmap => {
  36202. // check if there is an error for the cached promise
  36203. if ( _errorMap.has( cached ) === true ) {
  36204. if ( onError ) onError( _errorMap.get( cached ) );
  36205. scope.manager.itemError( url );
  36206. scope.manager.itemEnd( url );
  36207. } else {
  36208. if ( onLoad ) onLoad( imageBitmap );
  36209. scope.manager.itemEnd( url );
  36210. return imageBitmap;
  36211. }
  36212. } );
  36213. return;
  36214. }
  36215. // If cached is not a promise (i.e., it's already an imageBitmap)
  36216. setTimeout( function () {
  36217. if ( onLoad ) onLoad( cached );
  36218. scope.manager.itemEnd( url );
  36219. }, 0 );
  36220. return cached;
  36221. }
  36222. const fetchOptions = {};
  36223. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36224. fetchOptions.headers = this.requestHeader;
  36225. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36226. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36227. return res.blob();
  36228. } ).then( function ( blob ) {
  36229. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36230. } ).then( function ( imageBitmap ) {
  36231. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36232. if ( onLoad ) onLoad( imageBitmap );
  36233. scope.manager.itemEnd( url );
  36234. return imageBitmap;
  36235. } ).catch( function ( e ) {
  36236. if ( onError ) onError( e );
  36237. _errorMap.set( promise, e );
  36238. Cache.remove( `image-bitmap:${url}` );
  36239. scope.manager.itemError( url );
  36240. scope.manager.itemEnd( url );
  36241. } );
  36242. Cache.add( `image-bitmap:${url}`, promise );
  36243. scope.manager.itemStart( url );
  36244. }
  36245. /**
  36246. * Aborts ongoing fetch requests.
  36247. *
  36248. * @return {ImageBitmapLoader} A reference to this instance.
  36249. */
  36250. abort() {
  36251. this._abortController.abort();
  36252. this._abortController = new AbortController();
  36253. return this;
  36254. }
  36255. }
  36256. let _context;
  36257. /**
  36258. * Manages the global audio context in the engine.
  36259. *
  36260. * @hideconstructor
  36261. */
  36262. class AudioContext {
  36263. /**
  36264. * Returns the global native audio context.
  36265. *
  36266. * @return {AudioContext} The native audio context.
  36267. */
  36268. static getContext() {
  36269. if ( _context === undefined ) {
  36270. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36271. }
  36272. return _context;
  36273. }
  36274. /**
  36275. * Allows to set the global native audio context from outside.
  36276. *
  36277. * @param {AudioContext} value - The native context to set.
  36278. */
  36279. static setContext( value ) {
  36280. _context = value;
  36281. }
  36282. }
  36283. /**
  36284. * Class for loading audio buffers. Audios are internally
  36285. * loaded via {@link FileLoader}.
  36286. *
  36287. * ```js
  36288. * const audioListener = new THREE.AudioListener();
  36289. * const ambientSound = new THREE.Audio( audioListener );
  36290. *
  36291. * const loader = new THREE.AudioLoader();
  36292. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36293. *
  36294. * ambientSound.setBuffer( audioBuffer );
  36295. * ambientSound.play();
  36296. * ```
  36297. *
  36298. * @augments Loader
  36299. */
  36300. class AudioLoader extends Loader {
  36301. /**
  36302. * Constructs a new audio loader.
  36303. *
  36304. * @param {LoadingManager} [manager] - The loading manager.
  36305. */
  36306. constructor( manager ) {
  36307. super( manager );
  36308. }
  36309. /**
  36310. * Starts loading from the given URL and passes the loaded audio buffer
  36311. * to the `onLoad()` callback.
  36312. *
  36313. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36314. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36315. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36316. * @param {onErrorCallback} onError - Executed when errors occur.
  36317. */
  36318. load( url, onLoad, onProgress, onError ) {
  36319. const scope = this;
  36320. const loader = new FileLoader( this.manager );
  36321. loader.setResponseType( 'arraybuffer' );
  36322. loader.setPath( this.path );
  36323. loader.setRequestHeader( this.requestHeader );
  36324. loader.setWithCredentials( this.withCredentials );
  36325. loader.load( url, function ( buffer ) {
  36326. try {
  36327. // Create a copy of the buffer. The `decodeAudioData` method
  36328. // detaches the buffer when complete, preventing reuse.
  36329. const bufferCopy = buffer.slice( 0 );
  36330. const context = AudioContext.getContext();
  36331. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36332. onLoad( audioBuffer );
  36333. } ).catch( handleError );
  36334. } catch ( e ) {
  36335. handleError( e );
  36336. }
  36337. }, onProgress, onError );
  36338. function handleError( e ) {
  36339. if ( onError ) {
  36340. onError( e );
  36341. } else {
  36342. error( e );
  36343. }
  36344. scope.manager.itemError( url );
  36345. }
  36346. }
  36347. }
  36348. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36349. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36350. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36351. /**
  36352. * A special type of camera that uses two perspective cameras with
  36353. * stereoscopic projection. Can be used for rendering stereo effects
  36354. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36355. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36356. */
  36357. class StereoCamera {
  36358. /**
  36359. * Constructs a new stereo camera.
  36360. */
  36361. constructor() {
  36362. /**
  36363. * The type property is used for detecting the object type
  36364. * in context of serialization/deserialization.
  36365. *
  36366. * @type {string}
  36367. * @readonly
  36368. */
  36369. this.type = 'StereoCamera';
  36370. /**
  36371. * The aspect.
  36372. *
  36373. * @type {number}
  36374. * @default 1
  36375. */
  36376. this.aspect = 1;
  36377. /**
  36378. * The eye separation which represents the distance
  36379. * between the left and right camera.
  36380. *
  36381. * @type {number}
  36382. * @default 0.064
  36383. */
  36384. this.eyeSep = 0.064;
  36385. /**
  36386. * The camera representing the left eye. This is added to layer `1` so objects to be
  36387. * rendered by the left camera must also be added to this layer.
  36388. *
  36389. * @type {PerspectiveCamera}
  36390. */
  36391. this.cameraL = new PerspectiveCamera();
  36392. this.cameraL.layers.enable( 1 );
  36393. this.cameraL.matrixAutoUpdate = false;
  36394. /**
  36395. * The camera representing the right eye. This is added to layer `2` so objects to be
  36396. * rendered by the right camera must also be added to this layer.
  36397. *
  36398. * @type {PerspectiveCamera}
  36399. */
  36400. this.cameraR = new PerspectiveCamera();
  36401. this.cameraR.layers.enable( 2 );
  36402. this.cameraR.matrixAutoUpdate = false;
  36403. this._cache = {
  36404. focus: null,
  36405. fov: null,
  36406. aspect: null,
  36407. near: null,
  36408. far: null,
  36409. zoom: null,
  36410. eyeSep: null
  36411. };
  36412. }
  36413. /**
  36414. * Updates the stereo camera based on the given perspective camera.
  36415. *
  36416. * @param {PerspectiveCamera} camera - The perspective camera.
  36417. */
  36418. update( camera ) {
  36419. const cache = this._cache;
  36420. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36421. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36422. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36423. if ( needsUpdate ) {
  36424. cache.focus = camera.focus;
  36425. cache.fov = camera.fov;
  36426. cache.aspect = camera.aspect * this.aspect;
  36427. cache.near = camera.near;
  36428. cache.far = camera.far;
  36429. cache.zoom = camera.zoom;
  36430. cache.eyeSep = this.eyeSep;
  36431. // Off-axis stereoscopic effect based on
  36432. // http://paulbourke.net/stereographics/stereorender/
  36433. _projectionMatrix.copy( camera.projectionMatrix );
  36434. const eyeSepHalf = cache.eyeSep / 2;
  36435. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36436. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36437. let xmin, xmax;
  36438. // translate xOffset
  36439. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36440. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36441. // for left eye
  36442. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36443. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36444. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36445. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36446. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36447. // for right eye
  36448. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36449. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36450. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36451. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36452. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36453. }
  36454. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36455. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36456. }
  36457. }
  36458. /**
  36459. * This type of camera can be used in order to efficiently render a scene with a
  36460. * predefined set of cameras. This is an important performance aspect for
  36461. * rendering VR scenes.
  36462. *
  36463. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36464. * to define for each sub camera the `viewport` property which determines the
  36465. * part of the viewport that is rendered with this camera.
  36466. *
  36467. * @augments PerspectiveCamera
  36468. */
  36469. class ArrayCamera extends PerspectiveCamera {
  36470. /**
  36471. * Constructs a new array camera.
  36472. *
  36473. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36474. */
  36475. constructor( array = [] ) {
  36476. super();
  36477. /**
  36478. * This flag can be used for type testing.
  36479. *
  36480. * @type {boolean}
  36481. * @readonly
  36482. * @default true
  36483. */
  36484. this.isArrayCamera = true;
  36485. /**
  36486. * Whether this camera is used with multiview rendering or not.
  36487. *
  36488. * @type {boolean}
  36489. * @readonly
  36490. * @default false
  36491. */
  36492. this.isMultiViewCamera = false;
  36493. /**
  36494. * An array of perspective sub cameras.
  36495. *
  36496. * @type {Array<PerspectiveCamera>}
  36497. */
  36498. this.cameras = array;
  36499. }
  36500. }
  36501. /**
  36502. * Class for keeping track of time.
  36503. *
  36504. * @deprecated since r183.
  36505. */
  36506. class Clock {
  36507. /**
  36508. * Constructs a new clock.
  36509. *
  36510. * @deprecated since 183.
  36511. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36512. * `getDelta()` is called for the first time.
  36513. */
  36514. constructor( autoStart = true ) {
  36515. /**
  36516. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36517. * for the first time.
  36518. *
  36519. * @type {boolean}
  36520. * @default true
  36521. */
  36522. this.autoStart = autoStart;
  36523. /**
  36524. * Holds the time at which the clock's `start()` method was last called.
  36525. *
  36526. * @type {number}
  36527. * @default 0
  36528. */
  36529. this.startTime = 0;
  36530. /**
  36531. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36532. * `getDelta()` methods were last called.
  36533. *
  36534. * @type {number}
  36535. * @default 0
  36536. */
  36537. this.oldTime = 0;
  36538. /**
  36539. * Keeps track of the total time that the clock has been running.
  36540. *
  36541. * @type {number}
  36542. * @default 0
  36543. */
  36544. this.elapsedTime = 0;
  36545. /**
  36546. * Whether the clock is running or not.
  36547. *
  36548. * @type {boolean}
  36549. * @default true
  36550. */
  36551. this.running = false;
  36552. warn( 'THREE.Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  36553. }
  36554. /**
  36555. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36556. * called by the class.
  36557. */
  36558. start() {
  36559. this.startTime = performance.now();
  36560. this.oldTime = this.startTime;
  36561. this.elapsedTime = 0;
  36562. this.running = true;
  36563. }
  36564. /**
  36565. * Stops the clock.
  36566. */
  36567. stop() {
  36568. this.getElapsedTime();
  36569. this.running = false;
  36570. this.autoStart = false;
  36571. }
  36572. /**
  36573. * Returns the elapsed time in seconds.
  36574. *
  36575. * @return {number} The elapsed time.
  36576. */
  36577. getElapsedTime() {
  36578. this.getDelta();
  36579. return this.elapsedTime;
  36580. }
  36581. /**
  36582. * Returns the delta time in seconds.
  36583. *
  36584. * @return {number} The delta time.
  36585. */
  36586. getDelta() {
  36587. let diff = 0;
  36588. if ( this.autoStart && ! this.running ) {
  36589. this.start();
  36590. return 0;
  36591. }
  36592. if ( this.running ) {
  36593. const newTime = performance.now();
  36594. diff = ( newTime - this.oldTime ) / 1000;
  36595. this.oldTime = newTime;
  36596. this.elapsedTime += diff;
  36597. }
  36598. return diff;
  36599. }
  36600. }
  36601. const _position$1 = /*@__PURE__*/ new Vector3();
  36602. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36603. const _scale$1 = /*@__PURE__*/ new Vector3();
  36604. const _forward = /*@__PURE__*/ new Vector3();
  36605. const _up = /*@__PURE__*/ new Vector3();
  36606. /**
  36607. * The class represents a virtual listener of the all positional and non-positional audio effects
  36608. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36609. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36610. *
  36611. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36612. * camera represents the 3D transformation of the listener.
  36613. *
  36614. * @augments Object3D
  36615. */
  36616. class AudioListener extends Object3D {
  36617. /**
  36618. * Constructs a new audio listener.
  36619. */
  36620. constructor() {
  36621. super();
  36622. this.type = 'AudioListener';
  36623. /**
  36624. * The native audio context.
  36625. *
  36626. * @type {AudioContext}
  36627. * @readonly
  36628. */
  36629. this.context = AudioContext.getContext();
  36630. /**
  36631. * The gain node used for volume control.
  36632. *
  36633. * @type {GainNode}
  36634. * @readonly
  36635. */
  36636. this.gain = this.context.createGain();
  36637. this.gain.connect( this.context.destination );
  36638. /**
  36639. * An optional filter.
  36640. *
  36641. * Defined via {@link AudioListener#setFilter}.
  36642. *
  36643. * @type {?AudioNode}
  36644. * @default null
  36645. * @readonly
  36646. */
  36647. this.filter = null;
  36648. /**
  36649. * Time delta values required for `linearRampToValueAtTime()` usage.
  36650. *
  36651. * @type {number}
  36652. * @default 0
  36653. * @readonly
  36654. */
  36655. this.timeDelta = 0;
  36656. // private
  36657. this._clock = new Clock();
  36658. }
  36659. /**
  36660. * Returns the listener's input node.
  36661. *
  36662. * This method is used by other audio nodes to connect to this listener.
  36663. *
  36664. * @return {GainNode} The input node.
  36665. */
  36666. getInput() {
  36667. return this.gain;
  36668. }
  36669. /**
  36670. * Removes the current filter from this listener.
  36671. *
  36672. * @return {AudioListener} A reference to this listener.
  36673. */
  36674. removeFilter() {
  36675. if ( this.filter !== null ) {
  36676. this.gain.disconnect( this.filter );
  36677. this.filter.disconnect( this.context.destination );
  36678. this.gain.connect( this.context.destination );
  36679. this.filter = null;
  36680. }
  36681. return this;
  36682. }
  36683. /**
  36684. * Returns the current set filter.
  36685. *
  36686. * @return {?AudioNode} The filter.
  36687. */
  36688. getFilter() {
  36689. return this.filter;
  36690. }
  36691. /**
  36692. * Sets the given filter to this listener.
  36693. *
  36694. * @param {AudioNode} value - The filter to set.
  36695. * @return {AudioListener} A reference to this listener.
  36696. */
  36697. setFilter( value ) {
  36698. if ( this.filter !== null ) {
  36699. this.gain.disconnect( this.filter );
  36700. this.filter.disconnect( this.context.destination );
  36701. } else {
  36702. this.gain.disconnect( this.context.destination );
  36703. }
  36704. this.filter = value;
  36705. this.gain.connect( this.filter );
  36706. this.filter.connect( this.context.destination );
  36707. return this;
  36708. }
  36709. /**
  36710. * Returns the applications master volume.
  36711. *
  36712. * @return {number} The master volume.
  36713. */
  36714. getMasterVolume() {
  36715. return this.gain.gain.value;
  36716. }
  36717. /**
  36718. * Sets the applications master volume. This volume setting affects
  36719. * all audio nodes in the scene.
  36720. *
  36721. * @param {number} value - The master volume to set.
  36722. * @return {AudioListener} A reference to this listener.
  36723. */
  36724. setMasterVolume( value ) {
  36725. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36726. return this;
  36727. }
  36728. updateMatrixWorld( force ) {
  36729. super.updateMatrixWorld( force );
  36730. const listener = this.context.listener;
  36731. this.timeDelta = this._clock.getDelta();
  36732. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36733. // the initial forward and up directions must be orthogonal
  36734. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36735. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36736. if ( listener.positionX ) {
  36737. // code path for Chrome (see #14393)
  36738. const endTime = this.context.currentTime + this.timeDelta;
  36739. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36740. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36741. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36742. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36743. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36744. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36745. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36746. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36747. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36748. } else {
  36749. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36750. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36751. }
  36752. }
  36753. }
  36754. /**
  36755. * Represents a non-positional ( global ) audio object.
  36756. *
  36757. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36758. *
  36759. * ```js
  36760. * // create an AudioListener and add it to the camera
  36761. * const listener = new THREE.AudioListener();
  36762. * camera.add( listener );
  36763. *
  36764. * // create a global audio source
  36765. * const sound = new THREE.Audio( listener );
  36766. *
  36767. * // load a sound and set it as the Audio object's buffer
  36768. * const audioLoader = new THREE.AudioLoader();
  36769. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36770. * sound.setBuffer( buffer );
  36771. * sound.setLoop( true );
  36772. * sound.setVolume( 0.5 );
  36773. * sound.play();
  36774. * });
  36775. * ```
  36776. *
  36777. * @augments Object3D
  36778. */
  36779. class Audio extends Object3D {
  36780. /**
  36781. * Constructs a new audio.
  36782. *
  36783. * @param {AudioListener} listener - The global audio listener.
  36784. */
  36785. constructor( listener ) {
  36786. super();
  36787. this.type = 'Audio';
  36788. /**
  36789. * The global audio listener.
  36790. *
  36791. * @type {AudioListener}
  36792. * @readonly
  36793. */
  36794. this.listener = listener;
  36795. /**
  36796. * The audio context.
  36797. *
  36798. * @type {AudioContext}
  36799. * @readonly
  36800. */
  36801. this.context = listener.context;
  36802. /**
  36803. * The gain node used for volume control.
  36804. *
  36805. * @type {GainNode}
  36806. * @readonly
  36807. */
  36808. this.gain = this.context.createGain();
  36809. this.gain.connect( listener.getInput() );
  36810. /**
  36811. * Whether to start playback automatically or not.
  36812. *
  36813. * @type {boolean}
  36814. * @default false
  36815. */
  36816. this.autoplay = false;
  36817. /**
  36818. * A reference to an audio buffer.
  36819. *
  36820. * Defined via {@link Audio#setBuffer}.
  36821. *
  36822. * @type {?AudioBuffer}
  36823. * @default null
  36824. * @readonly
  36825. */
  36826. this.buffer = null;
  36827. /**
  36828. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36829. * +/- 1200 is an octave.
  36830. *
  36831. * Defined via {@link Audio#setDetune}.
  36832. *
  36833. * @type {number}
  36834. * @default 0
  36835. * @readonly
  36836. */
  36837. this.detune = 0;
  36838. /**
  36839. * Whether the audio should loop or not.
  36840. *
  36841. * Defined via {@link Audio#setLoop}.
  36842. *
  36843. * @type {boolean}
  36844. * @default false
  36845. * @readonly
  36846. */
  36847. this.loop = false;
  36848. /**
  36849. * Defines where in the audio buffer the replay should
  36850. * start, in seconds.
  36851. *
  36852. * @type {number}
  36853. * @default 0
  36854. */
  36855. this.loopStart = 0;
  36856. /**
  36857. * Defines where in the audio buffer the replay should
  36858. * stop, in seconds.
  36859. *
  36860. * @type {number}
  36861. * @default 0
  36862. */
  36863. this.loopEnd = 0;
  36864. /**
  36865. * An offset to the time within the audio buffer the playback
  36866. * should begin, in seconds.
  36867. *
  36868. * @type {number}
  36869. * @default 0
  36870. */
  36871. this.offset = 0;
  36872. /**
  36873. * Overrides the default duration of the audio.
  36874. *
  36875. * @type {undefined|number}
  36876. * @default undefined
  36877. */
  36878. this.duration = undefined;
  36879. /**
  36880. * The playback speed.
  36881. *
  36882. * Defined via {@link Audio#setPlaybackRate}.
  36883. *
  36884. * @type {number}
  36885. * @readonly
  36886. * @default 1
  36887. */
  36888. this.playbackRate = 1;
  36889. /**
  36890. * Indicates whether the audio is playing or not.
  36891. *
  36892. * This flag will be automatically set when using {@link Audio#play},
  36893. * {@link Audio#pause}, {@link Audio#stop}.
  36894. *
  36895. * @type {boolean}
  36896. * @readonly
  36897. * @default false
  36898. */
  36899. this.isPlaying = false;
  36900. /**
  36901. * Indicates whether the audio playback can be controlled
  36902. * with method like {@link Audio#play} or {@link Audio#pause}.
  36903. *
  36904. * This flag will be automatically set when audio sources are
  36905. * defined.
  36906. *
  36907. * @type {boolean}
  36908. * @readonly
  36909. * @default true
  36910. */
  36911. this.hasPlaybackControl = true;
  36912. /**
  36913. * Holds a reference to the current audio source.
  36914. *
  36915. * The property is automatically by one of the `set*()` methods.
  36916. *
  36917. * @type {?AudioNode}
  36918. * @readonly
  36919. * @default null
  36920. */
  36921. this.source = null;
  36922. /**
  36923. * Defines the source type.
  36924. *
  36925. * The property is automatically set by one of the `set*()` methods.
  36926. *
  36927. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36928. * @readonly
  36929. * @default 'empty'
  36930. */
  36931. this.sourceType = 'empty';
  36932. this._startedAt = 0;
  36933. this._progress = 0;
  36934. this._connected = false;
  36935. /**
  36936. * Can be used to apply a variety of low-order filters to create
  36937. * more complex sound effects e.g. via `BiquadFilterNode`.
  36938. *
  36939. * The property is automatically set by {@link Audio#setFilters}.
  36940. *
  36941. * @type {Array<AudioNode>}
  36942. * @readonly
  36943. */
  36944. this.filters = [];
  36945. }
  36946. /**
  36947. * Returns the output audio node.
  36948. *
  36949. * @return {GainNode} The output node.
  36950. */
  36951. getOutput() {
  36952. return this.gain;
  36953. }
  36954. /**
  36955. * Sets the given audio node as the source of this instance.
  36956. *
  36957. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36958. *
  36959. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36960. * @return {Audio} A reference to this instance.
  36961. */
  36962. setNodeSource( audioNode ) {
  36963. this.hasPlaybackControl = false;
  36964. this.sourceType = 'audioNode';
  36965. this.source = audioNode;
  36966. this.connect();
  36967. return this;
  36968. }
  36969. /**
  36970. * Sets the given media element as the source of this instance.
  36971. *
  36972. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36973. *
  36974. * @param {HTMLMediaElement} mediaElement - The media element.
  36975. * @return {Audio} A reference to this instance.
  36976. */
  36977. setMediaElementSource( mediaElement ) {
  36978. this.hasPlaybackControl = false;
  36979. this.sourceType = 'mediaNode';
  36980. this.source = this.context.createMediaElementSource( mediaElement );
  36981. this.connect();
  36982. return this;
  36983. }
  36984. /**
  36985. * Sets the given media stream as the source of this instance.
  36986. *
  36987. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36988. *
  36989. * @param {MediaStream} mediaStream - The media stream.
  36990. * @return {Audio} A reference to this instance.
  36991. */
  36992. setMediaStreamSource( mediaStream ) {
  36993. this.hasPlaybackControl = false;
  36994. this.sourceType = 'mediaStreamNode';
  36995. this.source = this.context.createMediaStreamSource( mediaStream );
  36996. this.connect();
  36997. return this;
  36998. }
  36999. /**
  37000. * Sets the given audio buffer as the source of this instance.
  37001. *
  37002. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37003. *
  37004. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37005. * @return {Audio} A reference to this instance.
  37006. */
  37007. setBuffer( audioBuffer ) {
  37008. this.buffer = audioBuffer;
  37009. this.sourceType = 'buffer';
  37010. if ( this.autoplay ) this.play();
  37011. return this;
  37012. }
  37013. /**
  37014. * Starts the playback of the audio.
  37015. *
  37016. * Can only be used with compatible audio sources that allow playback control.
  37017. *
  37018. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37019. * @return {Audio|undefined} A reference to this instance.
  37020. */
  37021. play( delay = 0 ) {
  37022. if ( this.isPlaying === true ) {
  37023. warn( 'Audio: Audio is already playing.' );
  37024. return;
  37025. }
  37026. if ( this.hasPlaybackControl === false ) {
  37027. warn( 'Audio: this Audio has no playback control.' );
  37028. return;
  37029. }
  37030. this._startedAt = this.context.currentTime + delay;
  37031. const source = this.context.createBufferSource();
  37032. source.buffer = this.buffer;
  37033. source.loop = this.loop;
  37034. source.loopStart = this.loopStart;
  37035. source.loopEnd = this.loopEnd;
  37036. source.onended = this.onEnded.bind( this );
  37037. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37038. this.isPlaying = true;
  37039. this.source = source;
  37040. this.setDetune( this.detune );
  37041. this.setPlaybackRate( this.playbackRate );
  37042. return this.connect();
  37043. }
  37044. /**
  37045. * Pauses the playback of the audio.
  37046. *
  37047. * Can only be used with compatible audio sources that allow playback control.
  37048. *
  37049. * @return {Audio|undefined} A reference to this instance.
  37050. */
  37051. pause() {
  37052. if ( this.hasPlaybackControl === false ) {
  37053. warn( 'Audio: this Audio has no playback control.' );
  37054. return;
  37055. }
  37056. if ( this.isPlaying === true ) {
  37057. // update current progress
  37058. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37059. if ( this.loop === true ) {
  37060. // ensure _progress does not exceed duration with looped audios
  37061. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37062. }
  37063. this.source.stop();
  37064. this.source.onended = null;
  37065. this.isPlaying = false;
  37066. }
  37067. return this;
  37068. }
  37069. /**
  37070. * Stops the playback of the audio.
  37071. *
  37072. * Can only be used with compatible audio sources that allow playback control.
  37073. *
  37074. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37075. * @return {Audio|undefined} A reference to this instance.
  37076. */
  37077. stop( delay = 0 ) {
  37078. if ( this.hasPlaybackControl === false ) {
  37079. warn( 'Audio: this Audio has no playback control.' );
  37080. return;
  37081. }
  37082. this._progress = 0;
  37083. if ( this.source !== null ) {
  37084. this.source.stop( this.context.currentTime + delay );
  37085. this.source.onended = null;
  37086. }
  37087. this.isPlaying = false;
  37088. return this;
  37089. }
  37090. /**
  37091. * Connects to the audio source. This is used internally on
  37092. * initialisation and when setting / removing filters.
  37093. *
  37094. * @return {Audio} A reference to this instance.
  37095. */
  37096. connect() {
  37097. if ( this.filters.length > 0 ) {
  37098. this.source.connect( this.filters[ 0 ] );
  37099. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37100. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37101. }
  37102. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37103. } else {
  37104. this.source.connect( this.getOutput() );
  37105. }
  37106. this._connected = true;
  37107. return this;
  37108. }
  37109. /**
  37110. * Disconnects to the audio source. This is used internally on
  37111. * initialisation and when setting / removing filters.
  37112. *
  37113. * @return {Audio|undefined} A reference to this instance.
  37114. */
  37115. disconnect() {
  37116. if ( this._connected === false ) {
  37117. return;
  37118. }
  37119. if ( this.filters.length > 0 ) {
  37120. this.source.disconnect( this.filters[ 0 ] );
  37121. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37122. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37123. }
  37124. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37125. } else {
  37126. this.source.disconnect( this.getOutput() );
  37127. }
  37128. this._connected = false;
  37129. return this;
  37130. }
  37131. /**
  37132. * Returns the current set filters.
  37133. *
  37134. * @return {Array<AudioNode>} The list of filters.
  37135. */
  37136. getFilters() {
  37137. return this.filters;
  37138. }
  37139. /**
  37140. * Sets an array of filters and connects them with the audio source.
  37141. *
  37142. * @param {Array<AudioNode>} [value] - A list of filters.
  37143. * @return {Audio} A reference to this instance.
  37144. */
  37145. setFilters( value ) {
  37146. if ( ! value ) value = [];
  37147. if ( this._connected === true ) {
  37148. this.disconnect();
  37149. this.filters = value.slice();
  37150. this.connect();
  37151. } else {
  37152. this.filters = value.slice();
  37153. }
  37154. return this;
  37155. }
  37156. /**
  37157. * Defines the detuning of oscillation in cents.
  37158. *
  37159. * @param {number} value - The detuning of oscillation in cents.
  37160. * @return {Audio} A reference to this instance.
  37161. */
  37162. setDetune( value ) {
  37163. this.detune = value;
  37164. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37165. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37166. }
  37167. return this;
  37168. }
  37169. /**
  37170. * Returns the detuning of oscillation in cents.
  37171. *
  37172. * @return {number} The detuning of oscillation in cents.
  37173. */
  37174. getDetune() {
  37175. return this.detune;
  37176. }
  37177. /**
  37178. * Returns the first filter in the list of filters.
  37179. *
  37180. * @return {AudioNode|undefined} The first filter in the list of filters.
  37181. */
  37182. getFilter() {
  37183. return this.getFilters()[ 0 ];
  37184. }
  37185. /**
  37186. * Applies a single filter node to the audio.
  37187. *
  37188. * @param {AudioNode} [filter] - The filter to set.
  37189. * @return {Audio} A reference to this instance.
  37190. */
  37191. setFilter( filter ) {
  37192. return this.setFilters( filter ? [ filter ] : [] );
  37193. }
  37194. /**
  37195. * Sets the playback rate.
  37196. *
  37197. * Can only be used with compatible audio sources that allow playback control.
  37198. *
  37199. * @param {number} [value] - The playback rate to set.
  37200. * @return {Audio|undefined} A reference to this instance.
  37201. */
  37202. setPlaybackRate( value ) {
  37203. if ( this.hasPlaybackControl === false ) {
  37204. warn( 'Audio: this Audio has no playback control.' );
  37205. return;
  37206. }
  37207. this.playbackRate = value;
  37208. if ( this.isPlaying === true ) {
  37209. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37210. }
  37211. return this;
  37212. }
  37213. /**
  37214. * Returns the current playback rate.
  37215. * @return {number} The playback rate.
  37216. */
  37217. getPlaybackRate() {
  37218. return this.playbackRate;
  37219. }
  37220. /**
  37221. * Automatically called when playback finished.
  37222. */
  37223. onEnded() {
  37224. this.isPlaying = false;
  37225. this._progress = 0;
  37226. }
  37227. /**
  37228. * Returns the loop flag.
  37229. *
  37230. * Can only be used with compatible audio sources that allow playback control.
  37231. *
  37232. * @return {boolean} Whether the audio should loop or not.
  37233. */
  37234. getLoop() {
  37235. if ( this.hasPlaybackControl === false ) {
  37236. warn( 'Audio: this Audio has no playback control.' );
  37237. return false;
  37238. }
  37239. return this.loop;
  37240. }
  37241. /**
  37242. * Sets the loop flag.
  37243. *
  37244. * Can only be used with compatible audio sources that allow playback control.
  37245. *
  37246. * @param {boolean} value - Whether the audio should loop or not.
  37247. * @return {Audio|undefined} A reference to this instance.
  37248. */
  37249. setLoop( value ) {
  37250. if ( this.hasPlaybackControl === false ) {
  37251. warn( 'Audio: this Audio has no playback control.' );
  37252. return;
  37253. }
  37254. this.loop = value;
  37255. if ( this.isPlaying === true ) {
  37256. this.source.loop = this.loop;
  37257. }
  37258. return this;
  37259. }
  37260. /**
  37261. * Sets the loop start value which defines where in the audio buffer the replay should
  37262. * start, in seconds.
  37263. *
  37264. * @param {number} value - The loop start value.
  37265. * @return {Audio} A reference to this instance.
  37266. */
  37267. setLoopStart( value ) {
  37268. this.loopStart = value;
  37269. return this;
  37270. }
  37271. /**
  37272. * Sets the loop end value which defines where in the audio buffer the replay should
  37273. * stop, in seconds.
  37274. *
  37275. * @param {number} value - The loop end value.
  37276. * @return {Audio} A reference to this instance.
  37277. */
  37278. setLoopEnd( value ) {
  37279. this.loopEnd = value;
  37280. return this;
  37281. }
  37282. /**
  37283. * Returns the volume.
  37284. *
  37285. * @return {number} The volume.
  37286. */
  37287. getVolume() {
  37288. return this.gain.gain.value;
  37289. }
  37290. /**
  37291. * Sets the volume.
  37292. *
  37293. * @param {number} value - The volume to set.
  37294. * @return {Audio} A reference to this instance.
  37295. */
  37296. setVolume( value ) {
  37297. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37298. return this;
  37299. }
  37300. copy( source, recursive ) {
  37301. super.copy( source, recursive );
  37302. if ( source.sourceType !== 'buffer' ) {
  37303. warn( 'Audio: Audio source type cannot be copied.' );
  37304. return this;
  37305. }
  37306. this.autoplay = source.autoplay;
  37307. this.buffer = source.buffer;
  37308. this.detune = source.detune;
  37309. this.loop = source.loop;
  37310. this.loopStart = source.loopStart;
  37311. this.loopEnd = source.loopEnd;
  37312. this.offset = source.offset;
  37313. this.duration = source.duration;
  37314. this.playbackRate = source.playbackRate;
  37315. this.hasPlaybackControl = source.hasPlaybackControl;
  37316. this.sourceType = source.sourceType;
  37317. this.filters = source.filters.slice();
  37318. return this;
  37319. }
  37320. clone( recursive ) {
  37321. return new this.constructor( this.listener ).copy( this, recursive );
  37322. }
  37323. }
  37324. const _position = /*@__PURE__*/ new Vector3();
  37325. const _quaternion = /*@__PURE__*/ new Quaternion();
  37326. const _scale = /*@__PURE__*/ new Vector3();
  37327. const _orientation = /*@__PURE__*/ new Vector3();
  37328. /**
  37329. * Represents a positional audio object.
  37330. *
  37331. * ```js
  37332. * // create an AudioListener and add it to the camera
  37333. * const listener = new THREE.AudioListener();
  37334. * camera.add( listener );
  37335. *
  37336. * // create the PositionalAudio object (passing in the listener)
  37337. * const sound = new THREE.PositionalAudio( listener );
  37338. *
  37339. * // load a sound and set it as the PositionalAudio object's buffer
  37340. * const audioLoader = new THREE.AudioLoader();
  37341. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37342. * sound.setBuffer( buffer );
  37343. * sound.setRefDistance( 20 );
  37344. * sound.play();
  37345. * });
  37346. *
  37347. * // create an object for the sound to play from
  37348. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37349. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37350. * const mesh = new THREE.Mesh( sphere, material );
  37351. * scene.add( mesh );
  37352. *
  37353. * // finally add the sound to the mesh
  37354. * mesh.add( sound );
  37355. *
  37356. * @augments Audio
  37357. */
  37358. class PositionalAudio extends Audio {
  37359. /**
  37360. * Constructs a positional audio.
  37361. *
  37362. * @param {AudioListener} listener - The global audio listener.
  37363. */
  37364. constructor( listener ) {
  37365. super( listener );
  37366. /**
  37367. * The panner node represents the location, direction, and behavior of an audio
  37368. * source in 3D space.
  37369. *
  37370. * @type {PannerNode}
  37371. * @readonly
  37372. */
  37373. this.panner = this.context.createPanner();
  37374. this.panner.panningModel = 'HRTF';
  37375. this.panner.connect( this.gain );
  37376. }
  37377. connect() {
  37378. super.connect();
  37379. this.panner.connect( this.gain );
  37380. return this;
  37381. }
  37382. disconnect() {
  37383. super.disconnect();
  37384. this.panner.disconnect( this.gain );
  37385. return this;
  37386. }
  37387. getOutput() {
  37388. return this.panner;
  37389. }
  37390. /**
  37391. * Returns the current reference distance.
  37392. *
  37393. * @return {number} The reference distance.
  37394. */
  37395. getRefDistance() {
  37396. return this.panner.refDistance;
  37397. }
  37398. /**
  37399. * Defines the reference distance for reducing volume as the audio source moves
  37400. * further from the listener – i.e. the distance at which the volume reduction
  37401. * starts taking effect.
  37402. *
  37403. * @param {number} value - The reference distance to set.
  37404. * @return {PositionalAudio} A reference to this instance.
  37405. */
  37406. setRefDistance( value ) {
  37407. this.panner.refDistance = value;
  37408. return this;
  37409. }
  37410. /**
  37411. * Returns the current rolloff factor.
  37412. *
  37413. * @return {number} The rolloff factor.
  37414. */
  37415. getRolloffFactor() {
  37416. return this.panner.rolloffFactor;
  37417. }
  37418. /**
  37419. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37420. *
  37421. * @param {number} value - The rolloff factor.
  37422. * @return {PositionalAudio} A reference to this instance.
  37423. */
  37424. setRolloffFactor( value ) {
  37425. this.panner.rolloffFactor = value;
  37426. return this;
  37427. }
  37428. /**
  37429. * Returns the current distance model.
  37430. *
  37431. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37432. */
  37433. getDistanceModel() {
  37434. return this.panner.distanceModel;
  37435. }
  37436. /**
  37437. * Defines which algorithm to use to reduce the volume of the audio source
  37438. * as it moves away from the listener.
  37439. *
  37440. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37441. * for more details.
  37442. *
  37443. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37444. * @return {PositionalAudio} A reference to this instance.
  37445. */
  37446. setDistanceModel( value ) {
  37447. this.panner.distanceModel = value;
  37448. return this;
  37449. }
  37450. /**
  37451. * Returns the current max distance.
  37452. *
  37453. * @return {number} The max distance.
  37454. */
  37455. getMaxDistance() {
  37456. return this.panner.maxDistance;
  37457. }
  37458. /**
  37459. * Defines the maximum distance between the audio source and the listener,
  37460. * after which the volume is not reduced any further.
  37461. *
  37462. * This value is used only by the `linear` distance model.
  37463. *
  37464. * @param {number} value - The max distance.
  37465. * @return {PositionalAudio} A reference to this instance.
  37466. */
  37467. setMaxDistance( value ) {
  37468. this.panner.maxDistance = value;
  37469. return this;
  37470. }
  37471. /**
  37472. * Sets the directional cone in which the audio can be listened.
  37473. *
  37474. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37475. * @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.
  37476. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37477. * @return {PositionalAudio} A reference to this instance.
  37478. */
  37479. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37480. this.panner.coneInnerAngle = coneInnerAngle;
  37481. this.panner.coneOuterAngle = coneOuterAngle;
  37482. this.panner.coneOuterGain = coneOuterGain;
  37483. return this;
  37484. }
  37485. updateMatrixWorld( force ) {
  37486. super.updateMatrixWorld( force );
  37487. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37488. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37489. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37490. const panner = this.panner;
  37491. if ( panner.positionX ) {
  37492. // code path for Chrome and Firefox (see #14393)
  37493. const endTime = this.context.currentTime + this.listener.timeDelta;
  37494. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37495. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37496. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37497. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37498. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37499. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37500. } else {
  37501. panner.setPosition( _position.x, _position.y, _position.z );
  37502. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37503. }
  37504. }
  37505. }
  37506. /**
  37507. * This class can be used to analyse audio data.
  37508. *
  37509. * ```js
  37510. * // create an AudioListener and add it to the camera
  37511. * const listener = new THREE.AudioListener();
  37512. * camera.add( listener );
  37513. *
  37514. * // create an Audio source
  37515. * const sound = new THREE.Audio( listener );
  37516. *
  37517. * // load a sound and set it as the Audio object's buffer
  37518. * const audioLoader = new THREE.AudioLoader();
  37519. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37520. * sound.setBuffer( buffer );
  37521. * sound.setLoop(true);
  37522. * sound.setVolume(0.5);
  37523. * sound.play();
  37524. * });
  37525. *
  37526. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37527. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37528. *
  37529. * // get the average frequency of the sound
  37530. * const data = analyser.getAverageFrequency();
  37531. * ```
  37532. */
  37533. class AudioAnalyser {
  37534. /**
  37535. * Constructs a new audio analyzer.
  37536. *
  37537. * @param {Audio} audio - The audio to analyze.
  37538. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37539. */
  37540. constructor( audio, fftSize = 2048 ) {
  37541. /**
  37542. * The global audio listener.
  37543. *
  37544. * @type {AnalyserNode}
  37545. */
  37546. this.analyser = audio.context.createAnalyser();
  37547. this.analyser.fftSize = fftSize;
  37548. /**
  37549. * Holds the analyzed data.
  37550. *
  37551. * @type {Uint8Array}
  37552. */
  37553. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37554. audio.getOutput().connect( this.analyser );
  37555. }
  37556. /**
  37557. * Returns an array with frequency data of the audio.
  37558. *
  37559. * Each item in the array represents the decibel value for a specific frequency.
  37560. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37561. * For example, for 48000 sample rate, the last item of the array will represent
  37562. * the decibel value for 24000 Hz.
  37563. *
  37564. * @return {Uint8Array} The frequency data.
  37565. */
  37566. getFrequencyData() {
  37567. this.analyser.getByteFrequencyData( this.data );
  37568. return this.data;
  37569. }
  37570. /**
  37571. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37572. *
  37573. * @return {number} The average frequency.
  37574. */
  37575. getAverageFrequency() {
  37576. let value = 0;
  37577. const data = this.getFrequencyData();
  37578. for ( let i = 0; i < data.length; i ++ ) {
  37579. value += data[ i ];
  37580. }
  37581. return value / data.length;
  37582. }
  37583. }
  37584. /**
  37585. * Buffered scene graph property that allows weighted accumulation; used internally.
  37586. */
  37587. class PropertyMixer {
  37588. /**
  37589. * Constructs a new property mixer.
  37590. *
  37591. * @param {PropertyBinding} binding - The property binding.
  37592. * @param {string} typeName - The keyframe track type name.
  37593. * @param {number} valueSize - The keyframe track value size.
  37594. */
  37595. constructor( binding, typeName, valueSize ) {
  37596. /**
  37597. * The property binding.
  37598. *
  37599. * @type {PropertyBinding}
  37600. */
  37601. this.binding = binding;
  37602. /**
  37603. * The keyframe track value size.
  37604. *
  37605. * @type {number}
  37606. */
  37607. this.valueSize = valueSize;
  37608. let mixFunction,
  37609. mixFunctionAdditive,
  37610. setIdentity;
  37611. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37612. //
  37613. // interpolators can use .buffer as their .result
  37614. // the data then goes to 'incoming'
  37615. //
  37616. // 'accu0' and 'accu1' are used frame-interleaved for
  37617. // the cumulative result and are compared to detect
  37618. // changes
  37619. //
  37620. // 'orig' stores the original state of the property
  37621. //
  37622. // 'add' is used for additive cumulative results
  37623. //
  37624. // 'work' is optional and is only present for quaternion types. It is used
  37625. // to store intermediate quaternion multiplication results
  37626. switch ( typeName ) {
  37627. case 'quaternion':
  37628. mixFunction = this._slerp;
  37629. mixFunctionAdditive = this._slerpAdditive;
  37630. setIdentity = this._setAdditiveIdentityQuaternion;
  37631. this.buffer = new Float64Array( valueSize * 6 );
  37632. this._workIndex = 5;
  37633. break;
  37634. case 'string':
  37635. case 'bool':
  37636. mixFunction = this._select;
  37637. // Use the regular mix function and for additive on these types,
  37638. // additive is not relevant for non-numeric types
  37639. mixFunctionAdditive = this._select;
  37640. setIdentity = this._setAdditiveIdentityOther;
  37641. this.buffer = new Array( valueSize * 5 );
  37642. break;
  37643. default:
  37644. mixFunction = this._lerp;
  37645. mixFunctionAdditive = this._lerpAdditive;
  37646. setIdentity = this._setAdditiveIdentityNumeric;
  37647. this.buffer = new Float64Array( valueSize * 5 );
  37648. }
  37649. this._mixBufferRegion = mixFunction;
  37650. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37651. this._setIdentity = setIdentity;
  37652. this._origIndex = 3;
  37653. this._addIndex = 4;
  37654. /**
  37655. * TODO
  37656. *
  37657. * @type {number}
  37658. * @default 0
  37659. */
  37660. this.cumulativeWeight = 0;
  37661. /**
  37662. * TODO
  37663. *
  37664. * @type {number}
  37665. * @default 0
  37666. */
  37667. this.cumulativeWeightAdditive = 0;
  37668. /**
  37669. * TODO
  37670. *
  37671. * @type {number}
  37672. * @default 0
  37673. */
  37674. this.useCount = 0;
  37675. /**
  37676. * TODO
  37677. *
  37678. * @type {number}
  37679. * @default 0
  37680. */
  37681. this.referenceCount = 0;
  37682. }
  37683. /**
  37684. * Accumulates data in the `incoming` region into `accu<i>`.
  37685. *
  37686. * @param {number} accuIndex - The accumulation index.
  37687. * @param {number} weight - The weight.
  37688. */
  37689. accumulate( accuIndex, weight ) {
  37690. // note: happily accumulating nothing when weight = 0, the caller knows
  37691. // the weight and shouldn't have made the call in the first place
  37692. const buffer = this.buffer,
  37693. stride = this.valueSize,
  37694. offset = accuIndex * stride + stride;
  37695. let currentWeight = this.cumulativeWeight;
  37696. if ( currentWeight === 0 ) {
  37697. // accuN := incoming * weight
  37698. for ( let i = 0; i !== stride; ++ i ) {
  37699. buffer[ offset + i ] = buffer[ i ];
  37700. }
  37701. currentWeight = weight;
  37702. } else {
  37703. // accuN := accuN + incoming * weight
  37704. currentWeight += weight;
  37705. const mix = weight / currentWeight;
  37706. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37707. }
  37708. this.cumulativeWeight = currentWeight;
  37709. }
  37710. /**
  37711. * Accumulates data in the `incoming` region into `add`.
  37712. *
  37713. * @param {number} weight - The weight.
  37714. */
  37715. accumulateAdditive( weight ) {
  37716. const buffer = this.buffer,
  37717. stride = this.valueSize,
  37718. offset = stride * this._addIndex;
  37719. if ( this.cumulativeWeightAdditive === 0 ) {
  37720. // add = identity
  37721. this._setIdentity();
  37722. }
  37723. // add := add + incoming * weight
  37724. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37725. this.cumulativeWeightAdditive += weight;
  37726. }
  37727. /**
  37728. * Applies the state of `accu<i>` to the binding when accus differ.
  37729. *
  37730. * @param {number} accuIndex - The accumulation index.
  37731. */
  37732. apply( accuIndex ) {
  37733. const stride = this.valueSize,
  37734. buffer = this.buffer,
  37735. offset = accuIndex * stride + stride,
  37736. weight = this.cumulativeWeight,
  37737. weightAdditive = this.cumulativeWeightAdditive,
  37738. binding = this.binding;
  37739. this.cumulativeWeight = 0;
  37740. this.cumulativeWeightAdditive = 0;
  37741. if ( weight < 1 ) {
  37742. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37743. const originalValueOffset = stride * this._origIndex;
  37744. this._mixBufferRegion(
  37745. buffer, offset, originalValueOffset, 1 - weight, stride );
  37746. }
  37747. if ( weightAdditive > 0 ) {
  37748. // accuN := accuN + additive accuN
  37749. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37750. }
  37751. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37752. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37753. // value has changed -> update scene graph
  37754. binding.setValue( buffer, offset );
  37755. break;
  37756. }
  37757. }
  37758. }
  37759. /**
  37760. * Remembers the state of the bound property and copy it to both accus.
  37761. */
  37762. saveOriginalState() {
  37763. const binding = this.binding;
  37764. const buffer = this.buffer,
  37765. stride = this.valueSize,
  37766. originalValueOffset = stride * this._origIndex;
  37767. binding.getValue( buffer, originalValueOffset );
  37768. // accu[0..1] := orig -- initially detect changes against the original
  37769. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37770. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37771. }
  37772. // Add to identity for additive
  37773. this._setIdentity();
  37774. this.cumulativeWeight = 0;
  37775. this.cumulativeWeightAdditive = 0;
  37776. }
  37777. /**
  37778. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37779. */
  37780. restoreOriginalState() {
  37781. const originalValueOffset = this.valueSize * 3;
  37782. this.binding.setValue( this.buffer, originalValueOffset );
  37783. }
  37784. // internals
  37785. _setAdditiveIdentityNumeric() {
  37786. const startIndex = this._addIndex * this.valueSize;
  37787. const endIndex = startIndex + this.valueSize;
  37788. for ( let i = startIndex; i < endIndex; i ++ ) {
  37789. this.buffer[ i ] = 0;
  37790. }
  37791. }
  37792. _setAdditiveIdentityQuaternion() {
  37793. this._setAdditiveIdentityNumeric();
  37794. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37795. }
  37796. _setAdditiveIdentityOther() {
  37797. const startIndex = this._origIndex * this.valueSize;
  37798. const targetIndex = this._addIndex * this.valueSize;
  37799. for ( let i = 0; i < this.valueSize; i ++ ) {
  37800. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37801. }
  37802. }
  37803. // mix functions
  37804. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37805. if ( t >= 0.5 ) {
  37806. for ( let i = 0; i !== stride; ++ i ) {
  37807. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37808. }
  37809. }
  37810. }
  37811. _slerp( buffer, dstOffset, srcOffset, t ) {
  37812. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37813. }
  37814. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37815. const workOffset = this._workIndex * stride;
  37816. // Store result in intermediate buffer offset
  37817. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37818. // Slerp to the intermediate result
  37819. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37820. }
  37821. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37822. const s = 1 - t;
  37823. for ( let i = 0; i !== stride; ++ i ) {
  37824. const j = dstOffset + i;
  37825. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37826. }
  37827. }
  37828. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37829. for ( let i = 0; i !== stride; ++ i ) {
  37830. const j = dstOffset + i;
  37831. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37832. }
  37833. }
  37834. }
  37835. // Characters [].:/ are reserved for track binding syntax.
  37836. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37837. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37838. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37839. // only latin characters, and the unicode \p{L} is not yet supported. So
  37840. // instead, we exclude reserved characters and match everything else.
  37841. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37842. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37843. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37844. // be matched to parse the rest of the track name.
  37845. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37846. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37847. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37848. // Object on target node, and accessor. May not contain reserved
  37849. // characters. Accessor may contain any character except closing bracket.
  37850. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37851. // Property and accessor. May not contain reserved characters. Accessor may
  37852. // contain any non-bracket characters.
  37853. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37854. const _trackRe = new RegExp( ''
  37855. + '^'
  37856. + _directoryRe
  37857. + _nodeRe
  37858. + _objectRe
  37859. + _propertyRe
  37860. + '$'
  37861. );
  37862. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37863. class Composite {
  37864. constructor( targetGroup, path, optionalParsedPath ) {
  37865. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37866. this._targetGroup = targetGroup;
  37867. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37868. }
  37869. getValue( array, offset ) {
  37870. this.bind(); // bind all binding
  37871. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37872. binding = this._bindings[ firstValidIndex ];
  37873. // and only call .getValue on the first
  37874. if ( binding !== undefined ) binding.getValue( array, offset );
  37875. }
  37876. setValue( array, offset ) {
  37877. const bindings = this._bindings;
  37878. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37879. bindings[ i ].setValue( array, offset );
  37880. }
  37881. }
  37882. bind() {
  37883. const bindings = this._bindings;
  37884. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37885. bindings[ i ].bind();
  37886. }
  37887. }
  37888. unbind() {
  37889. const bindings = this._bindings;
  37890. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37891. bindings[ i ].unbind();
  37892. }
  37893. }
  37894. }
  37895. // Note: This class uses a State pattern on a per-method basis:
  37896. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37897. // prototype version of these methods with one that represents
  37898. // the bound state. When the property is not found, the methods
  37899. // become no-ops.
  37900. /**
  37901. * This holds a reference to a real property in the scene graph; used internally.
  37902. */
  37903. class PropertyBinding {
  37904. /**
  37905. * Constructs a new property binding.
  37906. *
  37907. * @param {Object} rootNode - The root node.
  37908. * @param {string} path - The path.
  37909. * @param {?Object} [parsedPath] - The parsed path.
  37910. */
  37911. constructor( rootNode, path, parsedPath ) {
  37912. /**
  37913. * The object path to the animated property.
  37914. *
  37915. * @type {string}
  37916. */
  37917. this.path = path;
  37918. /**
  37919. * An object holding information about the path.
  37920. *
  37921. * @type {Object}
  37922. */
  37923. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37924. /**
  37925. * The object owns the animated property.
  37926. *
  37927. * @type {?Object}
  37928. */
  37929. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37930. /**
  37931. * The root node.
  37932. *
  37933. * @type {Object3D|Skeleton}
  37934. */
  37935. this.rootNode = rootNode;
  37936. // initial state of these methods that calls 'bind'
  37937. this.getValue = this._getValue_unbound;
  37938. this.setValue = this._setValue_unbound;
  37939. }
  37940. /**
  37941. * Factory method for creating a property binding from the given parameters.
  37942. *
  37943. * @static
  37944. * @param {Object} root - The root node.
  37945. * @param {string} path - The path.
  37946. * @param {?Object} [parsedPath] - The parsed path.
  37947. * @return {PropertyBinding|Composite} The created property binding or composite.
  37948. */
  37949. static create( root, path, parsedPath ) {
  37950. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37951. return new PropertyBinding( root, path, parsedPath );
  37952. } else {
  37953. return new PropertyBinding.Composite( root, path, parsedPath );
  37954. }
  37955. }
  37956. /**
  37957. * Replaces spaces with underscores and removes unsupported characters from
  37958. * node names, to ensure compatibility with parseTrackName().
  37959. *
  37960. * @param {string} name - Node name to be sanitized.
  37961. * @return {string} The sanitized node name.
  37962. */
  37963. static sanitizeNodeName( name ) {
  37964. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37965. }
  37966. /**
  37967. * Parses the given track name (an object path to an animated property) and
  37968. * returns an object with information about the path. Matches strings in the following forms:
  37969. *
  37970. * - nodeName.property
  37971. * - nodeName.property[accessor]
  37972. * - nodeName.material.property[accessor]
  37973. * - uuid.property[accessor]
  37974. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37975. * - parentName/nodeName.property
  37976. * - parentName/parentName/nodeName.property[index]
  37977. * - .bone[Armature.DEF_cog].position
  37978. * - scene:helium_balloon_model:helium_balloon_model.position
  37979. *
  37980. * @static
  37981. * @param {string} trackName - The track name to parse.
  37982. * @return {Object} The parsed track name as an object.
  37983. */
  37984. static parseTrackName( trackName ) {
  37985. const matches = _trackRe.exec( trackName );
  37986. if ( matches === null ) {
  37987. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37988. }
  37989. const results = {
  37990. // directoryName: matches[ 1 ], // (tschw) currently unused
  37991. nodeName: matches[ 2 ],
  37992. objectName: matches[ 3 ],
  37993. objectIndex: matches[ 4 ],
  37994. propertyName: matches[ 5 ], // required
  37995. propertyIndex: matches[ 6 ]
  37996. };
  37997. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37998. if ( lastDot !== undefined && lastDot !== -1 ) {
  37999. const objectName = results.nodeName.substring( lastDot + 1 );
  38000. // Object names must be checked against an allowlist. Otherwise, there
  38001. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38002. // 'bar' could be the objectName, or part of a nodeName (which can
  38003. // include '.' characters).
  38004. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38005. results.nodeName = results.nodeName.substring( 0, lastDot );
  38006. results.objectName = objectName;
  38007. }
  38008. }
  38009. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38010. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38011. }
  38012. return results;
  38013. }
  38014. /**
  38015. * Searches for a node in the hierarchy of the given root object by the given
  38016. * node name.
  38017. *
  38018. * @static
  38019. * @param {Object} root - The root object.
  38020. * @param {string|number} nodeName - The name of the node.
  38021. * @return {?Object} The found node. Returns `null` if no object was found.
  38022. */
  38023. static findNode( root, nodeName ) {
  38024. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38025. return root;
  38026. }
  38027. // search into skeleton bones.
  38028. if ( root.skeleton ) {
  38029. const bone = root.skeleton.getBoneByName( nodeName );
  38030. if ( bone !== undefined ) {
  38031. return bone;
  38032. }
  38033. }
  38034. // search into node subtree.
  38035. if ( root.children ) {
  38036. const searchNodeSubtree = function ( children ) {
  38037. for ( let i = 0; i < children.length; i ++ ) {
  38038. const childNode = children[ i ];
  38039. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38040. return childNode;
  38041. }
  38042. const result = searchNodeSubtree( childNode.children );
  38043. if ( result ) return result;
  38044. }
  38045. return null;
  38046. };
  38047. const subTreeNode = searchNodeSubtree( root.children );
  38048. if ( subTreeNode ) {
  38049. return subTreeNode;
  38050. }
  38051. }
  38052. return null;
  38053. }
  38054. // these are used to "bind" a nonexistent property
  38055. _getValue_unavailable() {}
  38056. _setValue_unavailable() {}
  38057. // Getters
  38058. _getValue_direct( buffer, offset ) {
  38059. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38060. }
  38061. _getValue_array( buffer, offset ) {
  38062. const source = this.resolvedProperty;
  38063. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38064. buffer[ offset ++ ] = source[ i ];
  38065. }
  38066. }
  38067. _getValue_arrayElement( buffer, offset ) {
  38068. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38069. }
  38070. _getValue_toArray( buffer, offset ) {
  38071. this.resolvedProperty.toArray( buffer, offset );
  38072. }
  38073. // Direct
  38074. _setValue_direct( buffer, offset ) {
  38075. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38076. }
  38077. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38078. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38079. this.targetObject.needsUpdate = true;
  38080. }
  38081. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38082. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38083. this.targetObject.matrixWorldNeedsUpdate = true;
  38084. }
  38085. // EntireArray
  38086. _setValue_array( buffer, offset ) {
  38087. const dest = this.resolvedProperty;
  38088. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38089. dest[ i ] = buffer[ offset ++ ];
  38090. }
  38091. }
  38092. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38093. const dest = this.resolvedProperty;
  38094. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38095. dest[ i ] = buffer[ offset ++ ];
  38096. }
  38097. this.targetObject.needsUpdate = true;
  38098. }
  38099. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38100. const dest = this.resolvedProperty;
  38101. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38102. dest[ i ] = buffer[ offset ++ ];
  38103. }
  38104. this.targetObject.matrixWorldNeedsUpdate = true;
  38105. }
  38106. // ArrayElement
  38107. _setValue_arrayElement( buffer, offset ) {
  38108. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38109. }
  38110. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38111. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38112. this.targetObject.needsUpdate = true;
  38113. }
  38114. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38115. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38116. this.targetObject.matrixWorldNeedsUpdate = true;
  38117. }
  38118. // HasToFromArray
  38119. _setValue_fromArray( buffer, offset ) {
  38120. this.resolvedProperty.fromArray( buffer, offset );
  38121. }
  38122. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38123. this.resolvedProperty.fromArray( buffer, offset );
  38124. this.targetObject.needsUpdate = true;
  38125. }
  38126. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38127. this.resolvedProperty.fromArray( buffer, offset );
  38128. this.targetObject.matrixWorldNeedsUpdate = true;
  38129. }
  38130. _getValue_unbound( targetArray, offset ) {
  38131. this.bind();
  38132. this.getValue( targetArray, offset );
  38133. }
  38134. _setValue_unbound( sourceArray, offset ) {
  38135. this.bind();
  38136. this.setValue( sourceArray, offset );
  38137. }
  38138. /**
  38139. * Creates a getter / setter pair for the property tracked by this binding.
  38140. */
  38141. bind() {
  38142. let targetObject = this.node;
  38143. const parsedPath = this.parsedPath;
  38144. const objectName = parsedPath.objectName;
  38145. const propertyName = parsedPath.propertyName;
  38146. let propertyIndex = parsedPath.propertyIndex;
  38147. if ( ! targetObject ) {
  38148. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38149. this.node = targetObject;
  38150. }
  38151. // set fail state so we can just 'return' on error
  38152. this.getValue = this._getValue_unavailable;
  38153. this.setValue = this._setValue_unavailable;
  38154. // ensure there is a value node
  38155. if ( ! targetObject ) {
  38156. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38157. return;
  38158. }
  38159. if ( objectName ) {
  38160. let objectIndex = parsedPath.objectIndex;
  38161. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38162. switch ( objectName ) {
  38163. case 'materials':
  38164. if ( ! targetObject.material ) {
  38165. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38166. return;
  38167. }
  38168. if ( ! targetObject.material.materials ) {
  38169. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38170. return;
  38171. }
  38172. targetObject = targetObject.material.materials;
  38173. break;
  38174. case 'bones':
  38175. if ( ! targetObject.skeleton ) {
  38176. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38177. return;
  38178. }
  38179. // potential future optimization: skip this if propertyIndex is already an integer
  38180. // and convert the integer string to a true integer.
  38181. targetObject = targetObject.skeleton.bones;
  38182. // support resolving morphTarget names into indices.
  38183. for ( let i = 0; i < targetObject.length; i ++ ) {
  38184. if ( targetObject[ i ].name === objectIndex ) {
  38185. objectIndex = i;
  38186. break;
  38187. }
  38188. }
  38189. break;
  38190. case 'map':
  38191. if ( 'map' in targetObject ) {
  38192. targetObject = targetObject.map;
  38193. break;
  38194. }
  38195. if ( ! targetObject.material ) {
  38196. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38197. return;
  38198. }
  38199. if ( ! targetObject.material.map ) {
  38200. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38201. return;
  38202. }
  38203. targetObject = targetObject.material.map;
  38204. break;
  38205. default:
  38206. if ( targetObject[ objectName ] === undefined ) {
  38207. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38208. return;
  38209. }
  38210. targetObject = targetObject[ objectName ];
  38211. }
  38212. if ( objectIndex !== undefined ) {
  38213. if ( targetObject[ objectIndex ] === undefined ) {
  38214. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38215. return;
  38216. }
  38217. targetObject = targetObject[ objectIndex ];
  38218. }
  38219. }
  38220. // resolve property
  38221. const nodeProperty = targetObject[ propertyName ];
  38222. if ( nodeProperty === undefined ) {
  38223. const nodeName = parsedPath.nodeName;
  38224. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38225. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38226. return;
  38227. }
  38228. // determine versioning scheme
  38229. let versioning = this.Versioning.None;
  38230. this.targetObject = targetObject;
  38231. if ( targetObject.isMaterial === true ) {
  38232. versioning = this.Versioning.NeedsUpdate;
  38233. } else if ( targetObject.isObject3D === true ) {
  38234. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38235. }
  38236. // determine how the property gets bound
  38237. let bindingType = this.BindingType.Direct;
  38238. if ( propertyIndex !== undefined ) {
  38239. // access a sub element of the property array (only primitives are supported right now)
  38240. if ( propertyName === 'morphTargetInfluences' ) {
  38241. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38242. // support resolving morphTarget names into indices.
  38243. if ( ! targetObject.geometry ) {
  38244. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38245. return;
  38246. }
  38247. if ( ! targetObject.geometry.morphAttributes ) {
  38248. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38249. return;
  38250. }
  38251. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38252. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38253. }
  38254. }
  38255. bindingType = this.BindingType.ArrayElement;
  38256. this.resolvedProperty = nodeProperty;
  38257. this.propertyIndex = propertyIndex;
  38258. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38259. // must use copy for Object3D.Euler/Quaternion
  38260. bindingType = this.BindingType.HasFromToArray;
  38261. this.resolvedProperty = nodeProperty;
  38262. } else if ( Array.isArray( nodeProperty ) ) {
  38263. bindingType = this.BindingType.EntireArray;
  38264. this.resolvedProperty = nodeProperty;
  38265. } else {
  38266. this.propertyName = propertyName;
  38267. }
  38268. // select getter / setter
  38269. this.getValue = this.GetterByBindingType[ bindingType ];
  38270. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38271. }
  38272. /**
  38273. * Unbinds the property.
  38274. */
  38275. unbind() {
  38276. this.node = null;
  38277. // back to the prototype version of getValue / setValue
  38278. // note: avoiding to mutate the shape of 'this' via 'delete'
  38279. this.getValue = this._getValue_unbound;
  38280. this.setValue = this._setValue_unbound;
  38281. }
  38282. }
  38283. PropertyBinding.Composite = Composite;
  38284. PropertyBinding.prototype.BindingType = {
  38285. Direct: 0,
  38286. EntireArray: 1,
  38287. ArrayElement: 2,
  38288. HasFromToArray: 3
  38289. };
  38290. PropertyBinding.prototype.Versioning = {
  38291. None: 0,
  38292. NeedsUpdate: 1,
  38293. MatrixWorldNeedsUpdate: 2
  38294. };
  38295. PropertyBinding.prototype.GetterByBindingType = [
  38296. PropertyBinding.prototype._getValue_direct,
  38297. PropertyBinding.prototype._getValue_array,
  38298. PropertyBinding.prototype._getValue_arrayElement,
  38299. PropertyBinding.prototype._getValue_toArray,
  38300. ];
  38301. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38302. [
  38303. // Direct
  38304. PropertyBinding.prototype._setValue_direct,
  38305. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38306. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38307. ], [
  38308. // EntireArray
  38309. PropertyBinding.prototype._setValue_array,
  38310. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38311. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38312. ], [
  38313. // ArrayElement
  38314. PropertyBinding.prototype._setValue_arrayElement,
  38315. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38316. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38317. ], [
  38318. // HasToFromArray
  38319. PropertyBinding.prototype._setValue_fromArray,
  38320. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38321. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38322. ]
  38323. ];
  38324. /**
  38325. * A group of objects that receives a shared animation state.
  38326. *
  38327. * Usage:
  38328. *
  38329. * - Add objects you would otherwise pass as 'root' to the
  38330. * constructor or the .clipAction method of AnimationMixer.
  38331. * - Instead pass this object as 'root'.
  38332. * - You can also add and remove objects later when the mixer is running.
  38333. *
  38334. * Note:
  38335. *
  38336. * - Objects of this class appear as one object to the mixer,
  38337. * so cache control of the individual objects must be done on the group.
  38338. *
  38339. * Limitation:
  38340. *
  38341. * - The animated properties must be compatible among the all objects in the group.
  38342. * - A single property can either be controlled through a target group or directly, but not both.
  38343. */
  38344. class AnimationObjectGroup {
  38345. /**
  38346. * Constructs a new animation group.
  38347. *
  38348. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38349. */
  38350. constructor() {
  38351. /**
  38352. * This flag can be used for type testing.
  38353. *
  38354. * @type {boolean}
  38355. * @readonly
  38356. * @default true
  38357. */
  38358. this.isAnimationObjectGroup = true;
  38359. /**
  38360. * The UUID of the 3D object.
  38361. *
  38362. * @type {string}
  38363. * @readonly
  38364. */
  38365. this.uuid = generateUUID();
  38366. // cached objects followed by the active ones
  38367. this._objects = Array.prototype.slice.call( arguments );
  38368. this.nCachedObjects_ = 0; // threshold
  38369. // note: read by PropertyBinding.Composite
  38370. const indices = {};
  38371. this._indicesByUUID = indices; // for bookkeeping
  38372. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38373. indices[ arguments[ i ].uuid ] = i;
  38374. }
  38375. this._paths = []; // inside: string
  38376. this._parsedPaths = []; // inside: { we don't care, here }
  38377. this._bindings = []; // inside: Array< PropertyBinding >
  38378. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38379. const scope = this;
  38380. this.stats = {
  38381. objects: {
  38382. get total() {
  38383. return scope._objects.length;
  38384. },
  38385. get inUse() {
  38386. return this.total - scope.nCachedObjects_;
  38387. }
  38388. },
  38389. get bindingsPerObject() {
  38390. return scope._bindings.length;
  38391. }
  38392. };
  38393. }
  38394. /**
  38395. * Adds an arbitrary number of objects to this animation group.
  38396. *
  38397. * @param {...Object3D} arguments - The 3D objects to add.
  38398. */
  38399. add() {
  38400. const objects = this._objects,
  38401. indicesByUUID = this._indicesByUUID,
  38402. paths = this._paths,
  38403. parsedPaths = this._parsedPaths,
  38404. bindings = this._bindings,
  38405. nBindings = bindings.length;
  38406. let knownObject = undefined,
  38407. nObjects = objects.length,
  38408. nCachedObjects = this.nCachedObjects_;
  38409. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38410. const object = arguments[ i ],
  38411. uuid = object.uuid;
  38412. let index = indicesByUUID[ uuid ];
  38413. if ( index === undefined ) {
  38414. // unknown object -> add it to the ACTIVE region
  38415. index = nObjects ++;
  38416. indicesByUUID[ uuid ] = index;
  38417. objects.push( object );
  38418. // accounting is done, now do the same for all bindings
  38419. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38420. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38421. }
  38422. } else if ( index < nCachedObjects ) {
  38423. knownObject = objects[ index ];
  38424. // move existing object to the ACTIVE region
  38425. const firstActiveIndex = -- nCachedObjects,
  38426. lastCachedObject = objects[ firstActiveIndex ];
  38427. indicesByUUID[ lastCachedObject.uuid ] = index;
  38428. objects[ index ] = lastCachedObject;
  38429. indicesByUUID[ uuid ] = firstActiveIndex;
  38430. objects[ firstActiveIndex ] = object;
  38431. // accounting is done, now do the same for all bindings
  38432. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38433. const bindingsForPath = bindings[ j ],
  38434. lastCached = bindingsForPath[ firstActiveIndex ];
  38435. let binding = bindingsForPath[ index ];
  38436. bindingsForPath[ index ] = lastCached;
  38437. if ( binding === undefined ) {
  38438. // since we do not bother to create new bindings
  38439. // for objects that are cached, the binding may
  38440. // or may not exist
  38441. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38442. }
  38443. bindingsForPath[ firstActiveIndex ] = binding;
  38444. }
  38445. } else if ( objects[ index ] !== knownObject ) {
  38446. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38447. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38448. } // else the object is already where we want it to be
  38449. } // for arguments
  38450. this.nCachedObjects_ = nCachedObjects;
  38451. }
  38452. /**
  38453. * Removes an arbitrary number of objects to this animation group
  38454. *
  38455. * @param {...Object3D} arguments - The 3D objects to remove.
  38456. */
  38457. remove() {
  38458. const objects = this._objects,
  38459. indicesByUUID = this._indicesByUUID,
  38460. bindings = this._bindings,
  38461. nBindings = bindings.length;
  38462. let nCachedObjects = this.nCachedObjects_;
  38463. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38464. const object = arguments[ i ],
  38465. uuid = object.uuid,
  38466. index = indicesByUUID[ uuid ];
  38467. if ( index !== undefined && index >= nCachedObjects ) {
  38468. // move existing object into the CACHED region
  38469. const lastCachedIndex = nCachedObjects ++,
  38470. firstActiveObject = objects[ lastCachedIndex ];
  38471. indicesByUUID[ firstActiveObject.uuid ] = index;
  38472. objects[ index ] = firstActiveObject;
  38473. indicesByUUID[ uuid ] = lastCachedIndex;
  38474. objects[ lastCachedIndex ] = object;
  38475. // accounting is done, now do the same for all bindings
  38476. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38477. const bindingsForPath = bindings[ j ],
  38478. firstActive = bindingsForPath[ lastCachedIndex ],
  38479. binding = bindingsForPath[ index ];
  38480. bindingsForPath[ index ] = firstActive;
  38481. bindingsForPath[ lastCachedIndex ] = binding;
  38482. }
  38483. }
  38484. } // for arguments
  38485. this.nCachedObjects_ = nCachedObjects;
  38486. }
  38487. /**
  38488. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38489. *
  38490. * @param {...Object3D} arguments - The 3D objects to uncache.
  38491. */
  38492. uncache() {
  38493. const objects = this._objects,
  38494. indicesByUUID = this._indicesByUUID,
  38495. bindings = this._bindings,
  38496. nBindings = bindings.length;
  38497. let nCachedObjects = this.nCachedObjects_,
  38498. nObjects = objects.length;
  38499. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38500. const object = arguments[ i ],
  38501. uuid = object.uuid,
  38502. index = indicesByUUID[ uuid ];
  38503. if ( index !== undefined ) {
  38504. delete indicesByUUID[ uuid ];
  38505. if ( index < nCachedObjects ) {
  38506. // object is cached, shrink the CACHED region
  38507. const firstActiveIndex = -- nCachedObjects,
  38508. lastCachedObject = objects[ firstActiveIndex ],
  38509. lastIndex = -- nObjects,
  38510. lastObject = objects[ lastIndex ];
  38511. // last cached object takes this object's place
  38512. indicesByUUID[ lastCachedObject.uuid ] = index;
  38513. objects[ index ] = lastCachedObject;
  38514. // last object goes to the activated slot and pop
  38515. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38516. objects[ firstActiveIndex ] = lastObject;
  38517. objects.pop();
  38518. // accounting is done, now do the same for all bindings
  38519. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38520. const bindingsForPath = bindings[ j ],
  38521. lastCached = bindingsForPath[ firstActiveIndex ],
  38522. last = bindingsForPath[ lastIndex ];
  38523. bindingsForPath[ index ] = lastCached;
  38524. bindingsForPath[ firstActiveIndex ] = last;
  38525. bindingsForPath.pop();
  38526. }
  38527. } else {
  38528. // object is active, just swap with the last and pop
  38529. const lastIndex = -- nObjects,
  38530. lastObject = objects[ lastIndex ];
  38531. if ( lastIndex > 0 ) {
  38532. indicesByUUID[ lastObject.uuid ] = index;
  38533. }
  38534. objects[ index ] = lastObject;
  38535. objects.pop();
  38536. // accounting is done, now do the same for all bindings
  38537. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38538. const bindingsForPath = bindings[ j ];
  38539. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38540. bindingsForPath.pop();
  38541. }
  38542. } // cached or active
  38543. } // if object is known
  38544. } // for arguments
  38545. this.nCachedObjects_ = nCachedObjects;
  38546. }
  38547. // Internal interface used by befriended PropertyBinding.Composite:
  38548. subscribe_( path, parsedPath ) {
  38549. // returns an array of bindings for the given path that is changed
  38550. // according to the contained objects in the group
  38551. const indicesByPath = this._bindingsIndicesByPath;
  38552. let index = indicesByPath[ path ];
  38553. const bindings = this._bindings;
  38554. if ( index !== undefined ) return bindings[ index ];
  38555. const paths = this._paths,
  38556. parsedPaths = this._parsedPaths,
  38557. objects = this._objects,
  38558. nObjects = objects.length,
  38559. nCachedObjects = this.nCachedObjects_,
  38560. bindingsForPath = new Array( nObjects );
  38561. index = bindings.length;
  38562. indicesByPath[ path ] = index;
  38563. paths.push( path );
  38564. parsedPaths.push( parsedPath );
  38565. bindings.push( bindingsForPath );
  38566. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38567. const object = objects[ i ];
  38568. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38569. }
  38570. return bindingsForPath;
  38571. }
  38572. unsubscribe_( path ) {
  38573. // tells the group to forget about a property path and no longer
  38574. // update the array previously obtained with 'subscribe_'
  38575. const indicesByPath = this._bindingsIndicesByPath,
  38576. index = indicesByPath[ path ];
  38577. if ( index !== undefined ) {
  38578. const paths = this._paths,
  38579. parsedPaths = this._parsedPaths,
  38580. bindings = this._bindings,
  38581. lastBindingsIndex = bindings.length - 1,
  38582. lastBindings = bindings[ lastBindingsIndex ],
  38583. lastBindingsPath = path[ lastBindingsIndex ];
  38584. indicesByPath[ lastBindingsPath ] = index;
  38585. bindings[ index ] = lastBindings;
  38586. bindings.pop();
  38587. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38588. parsedPaths.pop();
  38589. paths[ index ] = paths[ lastBindingsIndex ];
  38590. paths.pop();
  38591. }
  38592. }
  38593. }
  38594. /**
  38595. * An instance of `AnimationAction` schedules the playback of an animation which is
  38596. * stored in {@link AnimationClip}.
  38597. */
  38598. class AnimationAction {
  38599. /**
  38600. * Constructs a new animation action.
  38601. *
  38602. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38603. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38604. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38605. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38606. */
  38607. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38608. this._mixer = mixer;
  38609. this._clip = clip;
  38610. this._localRoot = localRoot;
  38611. /**
  38612. * Defines how the animation is blended/combined when two or more animations
  38613. * are simultaneously played.
  38614. *
  38615. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38616. */
  38617. this.blendMode = blendMode;
  38618. const tracks = clip.tracks,
  38619. nTracks = tracks.length,
  38620. interpolants = new Array( nTracks );
  38621. const interpolantSettings = {
  38622. endingStart: ZeroCurvatureEnding,
  38623. endingEnd: ZeroCurvatureEnding
  38624. };
  38625. for ( let i = 0; i !== nTracks; ++ i ) {
  38626. const interpolant = tracks[ i ].createInterpolant( null );
  38627. interpolants[ i ] = interpolant;
  38628. interpolant.settings = interpolantSettings;
  38629. }
  38630. this._interpolantSettings = interpolantSettings;
  38631. this._interpolants = interpolants; // bound by the mixer
  38632. // inside: PropertyMixer (managed by the mixer)
  38633. this._propertyBindings = new Array( nTracks );
  38634. this._cacheIndex = null; // for the memory manager
  38635. this._byClipCacheIndex = null; // for the memory manager
  38636. this._timeScaleInterpolant = null;
  38637. this._weightInterpolant = null;
  38638. /**
  38639. * The loop mode, set via {@link AnimationAction#setLoop}.
  38640. *
  38641. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38642. * @default LoopRepeat
  38643. */
  38644. this.loop = LoopRepeat;
  38645. this._loopCount = -1;
  38646. // global mixer time when the action is to be started
  38647. // it's set back to 'null' upon start of the action
  38648. this._startTime = null;
  38649. /**
  38650. * The local time of this action (in seconds, starting with `0`).
  38651. *
  38652. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38653. * loop state).
  38654. *
  38655. * @type {number}
  38656. * @default Infinity
  38657. */
  38658. this.time = 0;
  38659. /**
  38660. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38661. * animation to pause. Negative values cause the animation to play backwards.
  38662. *
  38663. * @type {number}
  38664. * @default 1
  38665. */
  38666. this.timeScale = 1;
  38667. this._effectiveTimeScale = 1;
  38668. /**
  38669. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38670. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38671. * several actions.
  38672. *
  38673. * @type {number}
  38674. * @default 1
  38675. */
  38676. this.weight = 1;
  38677. this._effectiveWeight = 1;
  38678. /**
  38679. * The number of repetitions of the performed clip over the course of this action.
  38680. * Can be set via {@link AnimationAction#setLoop}.
  38681. *
  38682. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38683. * `THREE:LoopOnce`.
  38684. *
  38685. * @type {number}
  38686. * @default Infinity
  38687. */
  38688. this.repetitions = Infinity;
  38689. /**
  38690. * If set to `true`, the playback of the action is paused.
  38691. *
  38692. * @type {boolean}
  38693. * @default false
  38694. */
  38695. this.paused = false;
  38696. /**
  38697. * If set to `false`, the action is disabled so it has no impact.
  38698. *
  38699. * When the action is re-enabled, the animation continues from its current
  38700. * time (setting `enabled` to `false` doesn't reset the action).
  38701. *
  38702. * @type {boolean}
  38703. * @default true
  38704. */
  38705. this.enabled = true;
  38706. /**
  38707. * If set to true the animation will automatically be paused on its last frame.
  38708. *
  38709. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38710. * to `false` when the last loop of the action has finished, so that this action has
  38711. * no further impact.
  38712. *
  38713. * Note: This member has no impact if the action is interrupted (it
  38714. * has only an effect if its last loop has really finished).
  38715. *
  38716. * @type {boolean}
  38717. * @default false
  38718. */
  38719. this.clampWhenFinished = false;
  38720. /**
  38721. * Enables smooth interpolation without separate clips for start, loop and end.
  38722. *
  38723. * @type {boolean}
  38724. * @default true
  38725. */
  38726. this.zeroSlopeAtStart = true;
  38727. /**
  38728. * Enables smooth interpolation without separate clips for start, loop and end.
  38729. *
  38730. * @type {boolean}
  38731. * @default true
  38732. */
  38733. this.zeroSlopeAtEnd = true;
  38734. }
  38735. /**
  38736. * Starts the playback of the animation.
  38737. *
  38738. * @return {AnimationAction} A reference to this animation action.
  38739. */
  38740. play() {
  38741. this._mixer._activateAction( this );
  38742. return this;
  38743. }
  38744. /**
  38745. * Stops the playback of the animation.
  38746. *
  38747. * @return {AnimationAction} A reference to this animation action.
  38748. */
  38749. stop() {
  38750. this._mixer._deactivateAction( this );
  38751. return this.reset();
  38752. }
  38753. /**
  38754. * Resets the playback of the animation.
  38755. *
  38756. * @return {AnimationAction} A reference to this animation action.
  38757. */
  38758. reset() {
  38759. this.paused = false;
  38760. this.enabled = true;
  38761. this.time = 0; // restart clip
  38762. this._loopCount = -1;// forget previous loops
  38763. this._startTime = null;// forget scheduling
  38764. return this.stopFading().stopWarping();
  38765. }
  38766. /**
  38767. * Returns `true` if the animation is running.
  38768. *
  38769. * @return {boolean} Whether the animation is running or not.
  38770. */
  38771. isRunning() {
  38772. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38773. this._startTime === null && this._mixer._isActiveAction( this );
  38774. }
  38775. /**
  38776. * Returns `true` when {@link AnimationAction#play} has been called.
  38777. *
  38778. * @return {boolean} Whether the animation is scheduled or not.
  38779. */
  38780. isScheduled() {
  38781. return this._mixer._isActiveAction( this );
  38782. }
  38783. /**
  38784. * Defines the time when the animation should start.
  38785. *
  38786. * @param {number} time - The start time in seconds.
  38787. * @return {AnimationAction} A reference to this animation action.
  38788. */
  38789. startAt( time ) {
  38790. this._startTime = time;
  38791. return this;
  38792. }
  38793. /**
  38794. * Configures the loop settings for this action.
  38795. *
  38796. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38797. * @param {number} repetitions - The number of repetitions.
  38798. * @return {AnimationAction} A reference to this animation action.
  38799. */
  38800. setLoop( mode, repetitions ) {
  38801. this.loop = mode;
  38802. this.repetitions = repetitions;
  38803. return this;
  38804. }
  38805. /**
  38806. * Sets the effective weight of this action.
  38807. *
  38808. * An action has no effect and thus an effective weight of zero when the
  38809. * action is disabled.
  38810. *
  38811. * @param {number} weight - The weight to set.
  38812. * @return {AnimationAction} A reference to this animation action.
  38813. */
  38814. setEffectiveWeight( weight ) {
  38815. this.weight = weight;
  38816. // note: same logic as when updated at runtime
  38817. this._effectiveWeight = this.enabled ? weight : 0;
  38818. return this.stopFading();
  38819. }
  38820. /**
  38821. * Returns the effective weight of this action.
  38822. *
  38823. * @return {number} The effective weight.
  38824. */
  38825. getEffectiveWeight() {
  38826. return this._effectiveWeight;
  38827. }
  38828. /**
  38829. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38830. * within the passed time interval.
  38831. *
  38832. * @param {number} duration - The duration of the fade.
  38833. * @return {AnimationAction} A reference to this animation action.
  38834. */
  38835. fadeIn( duration ) {
  38836. return this._scheduleFading( duration, 0, 1 );
  38837. }
  38838. /**
  38839. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38840. * within the passed time interval.
  38841. *
  38842. * @param {number} duration - The duration of the fade.
  38843. * @return {AnimationAction} A reference to this animation action.
  38844. */
  38845. fadeOut( duration ) {
  38846. return this._scheduleFading( duration, 1, 0 );
  38847. }
  38848. /**
  38849. * Causes this action to fade in and the given action to fade out,
  38850. * within the passed time interval.
  38851. *
  38852. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38853. * @param {number} duration - The duration of the fade.
  38854. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38855. * @return {AnimationAction} A reference to this animation action.
  38856. */
  38857. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38858. fadeOutAction.fadeOut( duration );
  38859. this.fadeIn( duration );
  38860. if ( warp === true ) {
  38861. const fadeInDuration = this._clip.duration,
  38862. fadeOutDuration = fadeOutAction._clip.duration,
  38863. startEndRatio = fadeOutDuration / fadeInDuration,
  38864. endStartRatio = fadeInDuration / fadeOutDuration;
  38865. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38866. this.warp( endStartRatio, 1.0, duration );
  38867. }
  38868. return this;
  38869. }
  38870. /**
  38871. * Causes this action to fade out and the given action to fade in,
  38872. * within the passed time interval.
  38873. *
  38874. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38875. * @param {number} duration - The duration of the fade.
  38876. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38877. * @return {AnimationAction} A reference to this animation action.
  38878. */
  38879. crossFadeTo( fadeInAction, duration, warp = false ) {
  38880. return fadeInAction.crossFadeFrom( this, duration, warp );
  38881. }
  38882. /**
  38883. * Stops any fading which is applied to this action.
  38884. *
  38885. * @return {AnimationAction} A reference to this animation action.
  38886. */
  38887. stopFading() {
  38888. const weightInterpolant = this._weightInterpolant;
  38889. if ( weightInterpolant !== null ) {
  38890. this._weightInterpolant = null;
  38891. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38892. }
  38893. return this;
  38894. }
  38895. /**
  38896. * Sets the effective time scale of this action.
  38897. *
  38898. * An action has no effect and thus an effective time scale of zero when the
  38899. * action is paused.
  38900. *
  38901. * @param {number} timeScale - The time scale to set.
  38902. * @return {AnimationAction} A reference to this animation action.
  38903. */
  38904. setEffectiveTimeScale( timeScale ) {
  38905. this.timeScale = timeScale;
  38906. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38907. return this.stopWarping();
  38908. }
  38909. /**
  38910. * Returns the effective time scale of this action.
  38911. *
  38912. * @return {number} The effective time scale.
  38913. */
  38914. getEffectiveTimeScale() {
  38915. return this._effectiveTimeScale;
  38916. }
  38917. /**
  38918. * Sets the duration for a single loop of this action.
  38919. *
  38920. * @param {number} duration - The duration to set.
  38921. * @return {AnimationAction} A reference to this animation action.
  38922. */
  38923. setDuration( duration ) {
  38924. this.timeScale = this._clip.duration / duration;
  38925. return this.stopWarping();
  38926. }
  38927. /**
  38928. * Synchronizes this action with the passed other action.
  38929. *
  38930. * @param {AnimationAction} action - The action to sync with.
  38931. * @return {AnimationAction} A reference to this animation action.
  38932. */
  38933. syncWith( action ) {
  38934. this.time = action.time;
  38935. this.timeScale = action.timeScale;
  38936. return this.stopWarping();
  38937. }
  38938. /**
  38939. * Decelerates this animation's speed to `0` within the passed time interval.
  38940. *
  38941. * @param {number} duration - The duration.
  38942. * @return {AnimationAction} A reference to this animation action.
  38943. */
  38944. halt( duration ) {
  38945. return this.warp( this._effectiveTimeScale, 0, duration );
  38946. }
  38947. /**
  38948. * Changes the playback speed, within the passed time interval, by modifying
  38949. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38950. * `endTimeScale`.
  38951. *
  38952. * @param {number} startTimeScale - The start time scale.
  38953. * @param {number} endTimeScale - The end time scale.
  38954. * @param {number} duration - The duration.
  38955. * @return {AnimationAction} A reference to this animation action.
  38956. */
  38957. warp( startTimeScale, endTimeScale, duration ) {
  38958. const mixer = this._mixer,
  38959. now = mixer.time,
  38960. timeScale = this.timeScale;
  38961. let interpolant = this._timeScaleInterpolant;
  38962. if ( interpolant === null ) {
  38963. interpolant = mixer._lendControlInterpolant();
  38964. this._timeScaleInterpolant = interpolant;
  38965. }
  38966. const times = interpolant.parameterPositions,
  38967. values = interpolant.sampleValues;
  38968. times[ 0 ] = now;
  38969. times[ 1 ] = now + duration;
  38970. values[ 0 ] = startTimeScale / timeScale;
  38971. values[ 1 ] = endTimeScale / timeScale;
  38972. return this;
  38973. }
  38974. /**
  38975. * Stops any scheduled warping which is applied to this action.
  38976. *
  38977. * @return {AnimationAction} A reference to this animation action.
  38978. */
  38979. stopWarping() {
  38980. const timeScaleInterpolant = this._timeScaleInterpolant;
  38981. if ( timeScaleInterpolant !== null ) {
  38982. this._timeScaleInterpolant = null;
  38983. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38984. }
  38985. return this;
  38986. }
  38987. /**
  38988. * Returns the animation mixer of this animation action.
  38989. *
  38990. * @return {AnimationMixer} The animation mixer.
  38991. */
  38992. getMixer() {
  38993. return this._mixer;
  38994. }
  38995. /**
  38996. * Returns the animation clip of this animation action.
  38997. *
  38998. * @return {AnimationClip} The animation clip.
  38999. */
  39000. getClip() {
  39001. return this._clip;
  39002. }
  39003. /**
  39004. * Returns the root object of this animation action.
  39005. *
  39006. * @return {Object3D} The root object.
  39007. */
  39008. getRoot() {
  39009. return this._localRoot || this._mixer._root;
  39010. }
  39011. // Internal
  39012. _update( time, deltaTime, timeDirection, accuIndex ) {
  39013. // called by the mixer
  39014. if ( ! this.enabled ) {
  39015. // call ._updateWeight() to update ._effectiveWeight
  39016. this._updateWeight( time );
  39017. return;
  39018. }
  39019. const startTime = this._startTime;
  39020. if ( startTime !== null ) {
  39021. // check for scheduled start of action
  39022. const timeRunning = ( time - startTime ) * timeDirection;
  39023. if ( timeRunning < 0 || timeDirection === 0 ) {
  39024. deltaTime = 0;
  39025. } else {
  39026. this._startTime = null; // unschedule
  39027. deltaTime = timeDirection * timeRunning;
  39028. }
  39029. }
  39030. // apply time scale and advance time
  39031. deltaTime *= this._updateTimeScale( time );
  39032. const clipTime = this._updateTime( deltaTime );
  39033. // note: _updateTime may disable the action resulting in
  39034. // an effective weight of 0
  39035. const weight = this._updateWeight( time );
  39036. if ( weight > 0 ) {
  39037. const interpolants = this._interpolants;
  39038. const propertyMixers = this._propertyBindings;
  39039. switch ( this.blendMode ) {
  39040. case AdditiveAnimationBlendMode:
  39041. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39042. interpolants[ j ].evaluate( clipTime );
  39043. propertyMixers[ j ].accumulateAdditive( weight );
  39044. }
  39045. break;
  39046. case NormalAnimationBlendMode:
  39047. default:
  39048. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39049. interpolants[ j ].evaluate( clipTime );
  39050. propertyMixers[ j ].accumulate( accuIndex, weight );
  39051. }
  39052. }
  39053. }
  39054. }
  39055. _updateWeight( time ) {
  39056. let weight = 0;
  39057. if ( this.enabled ) {
  39058. weight = this.weight;
  39059. const interpolant = this._weightInterpolant;
  39060. if ( interpolant !== null ) {
  39061. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39062. weight *= interpolantValue;
  39063. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39064. this.stopFading();
  39065. if ( interpolantValue === 0 ) {
  39066. // faded out, disable
  39067. this.enabled = false;
  39068. }
  39069. }
  39070. }
  39071. }
  39072. this._effectiveWeight = weight;
  39073. return weight;
  39074. }
  39075. _updateTimeScale( time ) {
  39076. let timeScale = 0;
  39077. if ( ! this.paused ) {
  39078. timeScale = this.timeScale;
  39079. const interpolant = this._timeScaleInterpolant;
  39080. if ( interpolant !== null ) {
  39081. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39082. timeScale *= interpolantValue;
  39083. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39084. this.stopWarping();
  39085. if ( timeScale === 0 ) {
  39086. // motion has halted, pause
  39087. this.paused = true;
  39088. } else {
  39089. // warp done - apply final time scale
  39090. this.timeScale = timeScale;
  39091. }
  39092. }
  39093. }
  39094. }
  39095. this._effectiveTimeScale = timeScale;
  39096. return timeScale;
  39097. }
  39098. _updateTime( deltaTime ) {
  39099. const duration = this._clip.duration;
  39100. const loop = this.loop;
  39101. let time = this.time + deltaTime;
  39102. let loopCount = this._loopCount;
  39103. const pingPong = ( loop === LoopPingPong );
  39104. if ( deltaTime === 0 ) {
  39105. if ( loopCount === -1 ) return time;
  39106. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39107. }
  39108. if ( loop === LoopOnce ) {
  39109. if ( loopCount === -1 ) {
  39110. // just started
  39111. this._loopCount = 0;
  39112. this._setEndings( true, true, false );
  39113. }
  39114. handle_stop: {
  39115. if ( time >= duration ) {
  39116. time = duration;
  39117. } else if ( time < 0 ) {
  39118. time = 0;
  39119. } else {
  39120. this.time = time;
  39121. break handle_stop;
  39122. }
  39123. if ( this.clampWhenFinished ) this.paused = true;
  39124. else this.enabled = false;
  39125. this.time = time;
  39126. this._mixer.dispatchEvent( {
  39127. type: 'finished', action: this,
  39128. direction: deltaTime < 0 ? -1 : 1
  39129. } );
  39130. }
  39131. } else { // repetitive Repeat or PingPong
  39132. if ( loopCount === -1 ) {
  39133. // just started
  39134. if ( deltaTime >= 0 ) {
  39135. loopCount = 0;
  39136. this._setEndings( true, this.repetitions === 0, pingPong );
  39137. } else {
  39138. // when looping in reverse direction, the initial
  39139. // transition through zero counts as a repetition,
  39140. // so leave loopCount at -1
  39141. this._setEndings( this.repetitions === 0, true, pingPong );
  39142. }
  39143. }
  39144. if ( time >= duration || time < 0 ) {
  39145. // wrap around
  39146. const loopDelta = Math.floor( time / duration ); // signed
  39147. time -= duration * loopDelta;
  39148. loopCount += Math.abs( loopDelta );
  39149. const pending = this.repetitions - loopCount;
  39150. if ( pending <= 0 ) {
  39151. // have to stop (switch state, clamp time, fire event)
  39152. if ( this.clampWhenFinished ) this.paused = true;
  39153. else this.enabled = false;
  39154. time = deltaTime > 0 ? duration : 0;
  39155. this.time = time;
  39156. this._mixer.dispatchEvent( {
  39157. type: 'finished', action: this,
  39158. direction: deltaTime > 0 ? 1 : -1
  39159. } );
  39160. } else {
  39161. // keep running
  39162. if ( pending === 1 ) {
  39163. // entering the last round
  39164. const atStart = deltaTime < 0;
  39165. this._setEndings( atStart, ! atStart, pingPong );
  39166. } else {
  39167. this._setEndings( false, false, pingPong );
  39168. }
  39169. this._loopCount = loopCount;
  39170. this.time = time;
  39171. this._mixer.dispatchEvent( {
  39172. type: 'loop', action: this, loopDelta: loopDelta
  39173. } );
  39174. }
  39175. } else {
  39176. this.time = time;
  39177. }
  39178. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39179. // invert time for the "pong round"
  39180. return duration - time;
  39181. }
  39182. }
  39183. return time;
  39184. }
  39185. _setEndings( atStart, atEnd, pingPong ) {
  39186. const settings = this._interpolantSettings;
  39187. if ( pingPong ) {
  39188. settings.endingStart = ZeroSlopeEnding;
  39189. settings.endingEnd = ZeroSlopeEnding;
  39190. } else {
  39191. // assuming for LoopOnce atStart == atEnd == true
  39192. if ( atStart ) {
  39193. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39194. } else {
  39195. settings.endingStart = WrapAroundEnding;
  39196. }
  39197. if ( atEnd ) {
  39198. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39199. } else {
  39200. settings.endingEnd = WrapAroundEnding;
  39201. }
  39202. }
  39203. }
  39204. _scheduleFading( duration, weightNow, weightThen ) {
  39205. const mixer = this._mixer, now = mixer.time;
  39206. let interpolant = this._weightInterpolant;
  39207. if ( interpolant === null ) {
  39208. interpolant = mixer._lendControlInterpolant();
  39209. this._weightInterpolant = interpolant;
  39210. }
  39211. const times = interpolant.parameterPositions,
  39212. values = interpolant.sampleValues;
  39213. times[ 0 ] = now;
  39214. values[ 0 ] = weightNow;
  39215. times[ 1 ] = now + duration;
  39216. values[ 1 ] = weightThen;
  39217. return this;
  39218. }
  39219. }
  39220. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39221. /**
  39222. * `AnimationMixer` is a player for animations on a particular object in
  39223. * the scene. When multiple objects in the scene are animated independently,
  39224. * one `AnimationMixer` may be used for each object.
  39225. */
  39226. class AnimationMixer extends EventDispatcher {
  39227. /**
  39228. * Constructs a new animation mixer.
  39229. *
  39230. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39231. */
  39232. constructor( root ) {
  39233. super();
  39234. this._root = root;
  39235. this._initMemoryManager();
  39236. this._accuIndex = 0;
  39237. /**
  39238. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39239. *
  39240. * @type {number}
  39241. * @default 0
  39242. */
  39243. this.time = 0;
  39244. /**
  39245. * A scaling factor for the global time.
  39246. *
  39247. * Note: Setting this member to `0` and later back to `1` is a
  39248. * possibility to pause/unpause all actions that are controlled by this
  39249. * mixer.
  39250. *
  39251. * @type {number}
  39252. * @default 1
  39253. */
  39254. this.timeScale = 1.0;
  39255. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39256. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39257. }
  39258. }
  39259. _bindAction( action, prototypeAction ) {
  39260. const root = action._localRoot || this._root,
  39261. tracks = action._clip.tracks,
  39262. nTracks = tracks.length,
  39263. bindings = action._propertyBindings,
  39264. interpolants = action._interpolants,
  39265. rootUuid = root.uuid,
  39266. bindingsByRoot = this._bindingsByRootAndName;
  39267. let bindingsByName = bindingsByRoot[ rootUuid ];
  39268. if ( bindingsByName === undefined ) {
  39269. bindingsByName = {};
  39270. bindingsByRoot[ rootUuid ] = bindingsByName;
  39271. }
  39272. for ( let i = 0; i !== nTracks; ++ i ) {
  39273. const track = tracks[ i ],
  39274. trackName = track.name;
  39275. let binding = bindingsByName[ trackName ];
  39276. if ( binding !== undefined ) {
  39277. ++ binding.referenceCount;
  39278. bindings[ i ] = binding;
  39279. } else {
  39280. binding = bindings[ i ];
  39281. if ( binding !== undefined ) {
  39282. // existing binding, make sure the cache knows
  39283. if ( binding._cacheIndex === null ) {
  39284. ++ binding.referenceCount;
  39285. this._addInactiveBinding( binding, rootUuid, trackName );
  39286. }
  39287. continue;
  39288. }
  39289. const path = prototypeAction && prototypeAction.
  39290. _propertyBindings[ i ].binding.parsedPath;
  39291. binding = new PropertyMixer(
  39292. PropertyBinding.create( root, trackName, path ),
  39293. track.ValueTypeName, track.getValueSize() );
  39294. ++ binding.referenceCount;
  39295. this._addInactiveBinding( binding, rootUuid, trackName );
  39296. bindings[ i ] = binding;
  39297. }
  39298. interpolants[ i ].resultBuffer = binding.buffer;
  39299. }
  39300. }
  39301. _activateAction( action ) {
  39302. if ( ! this._isActiveAction( action ) ) {
  39303. if ( action._cacheIndex === null ) {
  39304. // this action has been forgotten by the cache, but the user
  39305. // appears to be still using it -> rebind
  39306. const rootUuid = ( action._localRoot || this._root ).uuid,
  39307. clipUuid = action._clip.uuid,
  39308. actionsForClip = this._actionsByClip[ clipUuid ];
  39309. this._bindAction( action,
  39310. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39311. this._addInactiveAction( action, clipUuid, rootUuid );
  39312. }
  39313. const bindings = action._propertyBindings;
  39314. // increment reference counts / sort out state
  39315. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39316. const binding = bindings[ i ];
  39317. if ( binding.useCount ++ === 0 ) {
  39318. this._lendBinding( binding );
  39319. binding.saveOriginalState();
  39320. }
  39321. }
  39322. this._lendAction( action );
  39323. }
  39324. }
  39325. _deactivateAction( action ) {
  39326. if ( this._isActiveAction( action ) ) {
  39327. const bindings = action._propertyBindings;
  39328. // decrement reference counts / sort out state
  39329. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39330. const binding = bindings[ i ];
  39331. if ( -- binding.useCount === 0 ) {
  39332. binding.restoreOriginalState();
  39333. this._takeBackBinding( binding );
  39334. }
  39335. }
  39336. this._takeBackAction( action );
  39337. }
  39338. }
  39339. // Memory manager
  39340. _initMemoryManager() {
  39341. this._actions = []; // 'nActiveActions' followed by inactive ones
  39342. this._nActiveActions = 0;
  39343. this._actionsByClip = {};
  39344. // inside:
  39345. // {
  39346. // knownActions: Array< AnimationAction > - used as prototypes
  39347. // actionByRoot: AnimationAction - lookup
  39348. // }
  39349. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39350. this._nActiveBindings = 0;
  39351. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39352. this._controlInterpolants = []; // same game as above
  39353. this._nActiveControlInterpolants = 0;
  39354. const scope = this;
  39355. this.stats = {
  39356. actions: {
  39357. get total() {
  39358. return scope._actions.length;
  39359. },
  39360. get inUse() {
  39361. return scope._nActiveActions;
  39362. }
  39363. },
  39364. bindings: {
  39365. get total() {
  39366. return scope._bindings.length;
  39367. },
  39368. get inUse() {
  39369. return scope._nActiveBindings;
  39370. }
  39371. },
  39372. controlInterpolants: {
  39373. get total() {
  39374. return scope._controlInterpolants.length;
  39375. },
  39376. get inUse() {
  39377. return scope._nActiveControlInterpolants;
  39378. }
  39379. }
  39380. };
  39381. }
  39382. // Memory management for AnimationAction objects
  39383. _isActiveAction( action ) {
  39384. const index = action._cacheIndex;
  39385. return index !== null && index < this._nActiveActions;
  39386. }
  39387. _addInactiveAction( action, clipUuid, rootUuid ) {
  39388. const actions = this._actions,
  39389. actionsByClip = this._actionsByClip;
  39390. let actionsForClip = actionsByClip[ clipUuid ];
  39391. if ( actionsForClip === undefined ) {
  39392. actionsForClip = {
  39393. knownActions: [ action ],
  39394. actionByRoot: {}
  39395. };
  39396. action._byClipCacheIndex = 0;
  39397. actionsByClip[ clipUuid ] = actionsForClip;
  39398. } else {
  39399. const knownActions = actionsForClip.knownActions;
  39400. action._byClipCacheIndex = knownActions.length;
  39401. knownActions.push( action );
  39402. }
  39403. action._cacheIndex = actions.length;
  39404. actions.push( action );
  39405. actionsForClip.actionByRoot[ rootUuid ] = action;
  39406. }
  39407. _removeInactiveAction( action ) {
  39408. const actions = this._actions,
  39409. lastInactiveAction = actions[ actions.length - 1 ],
  39410. cacheIndex = action._cacheIndex;
  39411. lastInactiveAction._cacheIndex = cacheIndex;
  39412. actions[ cacheIndex ] = lastInactiveAction;
  39413. actions.pop();
  39414. action._cacheIndex = null;
  39415. const clipUuid = action._clip.uuid,
  39416. actionsByClip = this._actionsByClip,
  39417. actionsForClip = actionsByClip[ clipUuid ],
  39418. knownActionsForClip = actionsForClip.knownActions,
  39419. lastKnownAction =
  39420. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39421. byClipCacheIndex = action._byClipCacheIndex;
  39422. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39423. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39424. knownActionsForClip.pop();
  39425. action._byClipCacheIndex = null;
  39426. const actionByRoot = actionsForClip.actionByRoot,
  39427. rootUuid = ( action._localRoot || this._root ).uuid;
  39428. delete actionByRoot[ rootUuid ];
  39429. if ( knownActionsForClip.length === 0 ) {
  39430. delete actionsByClip[ clipUuid ];
  39431. }
  39432. this._removeInactiveBindingsForAction( action );
  39433. }
  39434. _removeInactiveBindingsForAction( action ) {
  39435. const bindings = action._propertyBindings;
  39436. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39437. const binding = bindings[ i ];
  39438. if ( -- binding.referenceCount === 0 ) {
  39439. this._removeInactiveBinding( binding );
  39440. }
  39441. }
  39442. }
  39443. _lendAction( action ) {
  39444. // [ active actions | inactive actions ]
  39445. // [ active actions >| inactive actions ]
  39446. // s a
  39447. // <-swap->
  39448. // a s
  39449. const actions = this._actions,
  39450. prevIndex = action._cacheIndex,
  39451. lastActiveIndex = this._nActiveActions ++,
  39452. firstInactiveAction = actions[ lastActiveIndex ];
  39453. action._cacheIndex = lastActiveIndex;
  39454. actions[ lastActiveIndex ] = action;
  39455. firstInactiveAction._cacheIndex = prevIndex;
  39456. actions[ prevIndex ] = firstInactiveAction;
  39457. }
  39458. _takeBackAction( action ) {
  39459. // [ active actions | inactive actions ]
  39460. // [ active actions |< inactive actions ]
  39461. // a s
  39462. // <-swap->
  39463. // s a
  39464. const actions = this._actions,
  39465. prevIndex = action._cacheIndex,
  39466. firstInactiveIndex = -- this._nActiveActions,
  39467. lastActiveAction = actions[ firstInactiveIndex ];
  39468. action._cacheIndex = firstInactiveIndex;
  39469. actions[ firstInactiveIndex ] = action;
  39470. lastActiveAction._cacheIndex = prevIndex;
  39471. actions[ prevIndex ] = lastActiveAction;
  39472. }
  39473. // Memory management for PropertyMixer objects
  39474. _addInactiveBinding( binding, rootUuid, trackName ) {
  39475. const bindingsByRoot = this._bindingsByRootAndName,
  39476. bindings = this._bindings;
  39477. let bindingByName = bindingsByRoot[ rootUuid ];
  39478. if ( bindingByName === undefined ) {
  39479. bindingByName = {};
  39480. bindingsByRoot[ rootUuid ] = bindingByName;
  39481. }
  39482. bindingByName[ trackName ] = binding;
  39483. binding._cacheIndex = bindings.length;
  39484. bindings.push( binding );
  39485. }
  39486. _removeInactiveBinding( binding ) {
  39487. const bindings = this._bindings,
  39488. propBinding = binding.binding,
  39489. rootUuid = propBinding.rootNode.uuid,
  39490. trackName = propBinding.path,
  39491. bindingsByRoot = this._bindingsByRootAndName,
  39492. bindingByName = bindingsByRoot[ rootUuid ],
  39493. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39494. cacheIndex = binding._cacheIndex;
  39495. lastInactiveBinding._cacheIndex = cacheIndex;
  39496. bindings[ cacheIndex ] = lastInactiveBinding;
  39497. bindings.pop();
  39498. delete bindingByName[ trackName ];
  39499. if ( Object.keys( bindingByName ).length === 0 ) {
  39500. delete bindingsByRoot[ rootUuid ];
  39501. }
  39502. }
  39503. _lendBinding( binding ) {
  39504. const bindings = this._bindings,
  39505. prevIndex = binding._cacheIndex,
  39506. lastActiveIndex = this._nActiveBindings ++,
  39507. firstInactiveBinding = bindings[ lastActiveIndex ];
  39508. binding._cacheIndex = lastActiveIndex;
  39509. bindings[ lastActiveIndex ] = binding;
  39510. firstInactiveBinding._cacheIndex = prevIndex;
  39511. bindings[ prevIndex ] = firstInactiveBinding;
  39512. }
  39513. _takeBackBinding( binding ) {
  39514. const bindings = this._bindings,
  39515. prevIndex = binding._cacheIndex,
  39516. firstInactiveIndex = -- this._nActiveBindings,
  39517. lastActiveBinding = bindings[ firstInactiveIndex ];
  39518. binding._cacheIndex = firstInactiveIndex;
  39519. bindings[ firstInactiveIndex ] = binding;
  39520. lastActiveBinding._cacheIndex = prevIndex;
  39521. bindings[ prevIndex ] = lastActiveBinding;
  39522. }
  39523. // Memory management of Interpolants for weight and time scale
  39524. _lendControlInterpolant() {
  39525. const interpolants = this._controlInterpolants,
  39526. lastActiveIndex = this._nActiveControlInterpolants ++;
  39527. let interpolant = interpolants[ lastActiveIndex ];
  39528. if ( interpolant === undefined ) {
  39529. interpolant = new LinearInterpolant(
  39530. new Float32Array( 2 ), new Float32Array( 2 ),
  39531. 1, _controlInterpolantsResultBuffer );
  39532. interpolant.__cacheIndex = lastActiveIndex;
  39533. interpolants[ lastActiveIndex ] = interpolant;
  39534. }
  39535. return interpolant;
  39536. }
  39537. _takeBackControlInterpolant( interpolant ) {
  39538. const interpolants = this._controlInterpolants,
  39539. prevIndex = interpolant.__cacheIndex,
  39540. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39541. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39542. interpolant.__cacheIndex = firstInactiveIndex;
  39543. interpolants[ firstInactiveIndex ] = interpolant;
  39544. lastActiveInterpolant.__cacheIndex = prevIndex;
  39545. interpolants[ prevIndex ] = lastActiveInterpolant;
  39546. }
  39547. /**
  39548. * Returns an instance of {@link AnimationAction} for the passed clip.
  39549. *
  39550. * If an action fitting the clip and root parameters doesn't yet exist, it
  39551. * will be created by this method. Calling this method several times with the
  39552. * same clip and root parameters always returns the same action.
  39553. *
  39554. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39555. * @param {Object3D} [optionalRoot] - An alternative root object.
  39556. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39557. * @return {?AnimationAction} The animation action.
  39558. */
  39559. clipAction( clip, optionalRoot, blendMode ) {
  39560. const root = optionalRoot || this._root,
  39561. rootUuid = root.uuid;
  39562. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39563. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39564. const actionsForClip = this._actionsByClip[ clipUuid ];
  39565. let prototypeAction = null;
  39566. if ( blendMode === undefined ) {
  39567. if ( clipObject !== null ) {
  39568. blendMode = clipObject.blendMode;
  39569. } else {
  39570. blendMode = NormalAnimationBlendMode;
  39571. }
  39572. }
  39573. if ( actionsForClip !== undefined ) {
  39574. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39575. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39576. return existingAction;
  39577. }
  39578. // we know the clip, so we don't have to parse all
  39579. // the bindings again but can just copy
  39580. prototypeAction = actionsForClip.knownActions[ 0 ];
  39581. // also, take the clip from the prototype action
  39582. if ( clipObject === null )
  39583. clipObject = prototypeAction._clip;
  39584. }
  39585. // clip must be known when specified via string
  39586. if ( clipObject === null ) return null;
  39587. // allocate all resources required to run it
  39588. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39589. this._bindAction( newAction, prototypeAction );
  39590. // and make the action known to the memory manager
  39591. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39592. return newAction;
  39593. }
  39594. /**
  39595. * Returns an existing animation action for the passed clip.
  39596. *
  39597. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39598. * @param {Object3D} [optionalRoot] - An alternative root object.
  39599. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39600. */
  39601. existingAction( clip, optionalRoot ) {
  39602. const root = optionalRoot || this._root,
  39603. rootUuid = root.uuid,
  39604. clipObject = typeof clip === 'string' ?
  39605. AnimationClip.findByName( root, clip ) : clip,
  39606. clipUuid = clipObject ? clipObject.uuid : clip,
  39607. actionsForClip = this._actionsByClip[ clipUuid ];
  39608. if ( actionsForClip !== undefined ) {
  39609. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39610. }
  39611. return null;
  39612. }
  39613. /**
  39614. * Deactivates all previously scheduled actions on this mixer.
  39615. *
  39616. * @return {AnimationMixer} A reference to this animation mixer.
  39617. */
  39618. stopAllAction() {
  39619. const actions = this._actions,
  39620. nActions = this._nActiveActions;
  39621. for ( let i = nActions - 1; i >= 0; -- i ) {
  39622. actions[ i ].stop();
  39623. }
  39624. return this;
  39625. }
  39626. /**
  39627. * Advances the global mixer time and updates the animation.
  39628. *
  39629. * This is usually done in the render loop by passing the delta
  39630. * time from {@link Clock} or {@link Timer}.
  39631. *
  39632. * @param {number} deltaTime - The delta time in seconds.
  39633. * @return {AnimationMixer} A reference to this animation mixer.
  39634. */
  39635. update( deltaTime ) {
  39636. deltaTime *= this.timeScale;
  39637. const actions = this._actions,
  39638. nActions = this._nActiveActions,
  39639. time = this.time += deltaTime,
  39640. timeDirection = Math.sign( deltaTime ),
  39641. accuIndex = this._accuIndex ^= 1;
  39642. // run active actions
  39643. for ( let i = 0; i !== nActions; ++ i ) {
  39644. const action = actions[ i ];
  39645. action._update( time, deltaTime, timeDirection, accuIndex );
  39646. }
  39647. // update scene graph
  39648. const bindings = this._bindings,
  39649. nBindings = this._nActiveBindings;
  39650. for ( let i = 0; i !== nBindings; ++ i ) {
  39651. bindings[ i ].apply( accuIndex );
  39652. }
  39653. return this;
  39654. }
  39655. /**
  39656. * Sets the global mixer to a specific time and updates the animation accordingly.
  39657. *
  39658. * This is useful when you need to jump to an exact time in an animation. The
  39659. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39660. *
  39661. * @param {number} time - The time to set in seconds.
  39662. * @return {AnimationMixer} A reference to this animation mixer.
  39663. */
  39664. setTime( time ) {
  39665. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39666. for ( let i = 0; i < this._actions.length; i ++ ) {
  39667. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39668. }
  39669. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39670. }
  39671. /**
  39672. * Returns this mixer's root object.
  39673. *
  39674. * @return {Object3D} The mixer's root object.
  39675. */
  39676. getRoot() {
  39677. return this._root;
  39678. }
  39679. /**
  39680. * Deallocates all memory resources for a clip. Before using this method make
  39681. * sure to call {@link AnimationAction#stop} for all related actions.
  39682. *
  39683. * @param {AnimationClip} clip - The clip to uncache.
  39684. */
  39685. uncacheClip( clip ) {
  39686. const actions = this._actions,
  39687. clipUuid = clip.uuid,
  39688. actionsByClip = this._actionsByClip,
  39689. actionsForClip = actionsByClip[ clipUuid ];
  39690. if ( actionsForClip !== undefined ) {
  39691. // note: just calling _removeInactiveAction would mess up the
  39692. // iteration state and also require updating the state we can
  39693. // just throw away
  39694. const actionsToRemove = actionsForClip.knownActions;
  39695. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39696. const action = actionsToRemove[ i ];
  39697. this._deactivateAction( action );
  39698. const cacheIndex = action._cacheIndex,
  39699. lastInactiveAction = actions[ actions.length - 1 ];
  39700. action._cacheIndex = null;
  39701. action._byClipCacheIndex = null;
  39702. lastInactiveAction._cacheIndex = cacheIndex;
  39703. actions[ cacheIndex ] = lastInactiveAction;
  39704. actions.pop();
  39705. this._removeInactiveBindingsForAction( action );
  39706. }
  39707. delete actionsByClip[ clipUuid ];
  39708. }
  39709. }
  39710. /**
  39711. * Deallocates all memory resources for a root object. Before using this
  39712. * method make sure to call {@link AnimationAction#stop} for all related
  39713. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39714. * mixer operates on a single root.
  39715. *
  39716. * @param {Object3D} root - The root object to uncache.
  39717. */
  39718. uncacheRoot( root ) {
  39719. const rootUuid = root.uuid,
  39720. actionsByClip = this._actionsByClip;
  39721. for ( const clipUuid in actionsByClip ) {
  39722. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39723. action = actionByRoot[ rootUuid ];
  39724. if ( action !== undefined ) {
  39725. this._deactivateAction( action );
  39726. this._removeInactiveAction( action );
  39727. }
  39728. }
  39729. const bindingsByRoot = this._bindingsByRootAndName,
  39730. bindingByName = bindingsByRoot[ rootUuid ];
  39731. if ( bindingByName !== undefined ) {
  39732. for ( const trackName in bindingByName ) {
  39733. const binding = bindingByName[ trackName ];
  39734. binding.restoreOriginalState();
  39735. this._removeInactiveBinding( binding );
  39736. }
  39737. }
  39738. }
  39739. /**
  39740. * Deallocates all memory resources for an action. The action is identified by the
  39741. * given clip and an optional root object. Before using this method make
  39742. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39743. *
  39744. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39745. * @param {Object3D} [optionalRoot] - An alternative root object.
  39746. */
  39747. uncacheAction( clip, optionalRoot ) {
  39748. const action = this.existingAction( clip, optionalRoot );
  39749. if ( action !== null ) {
  39750. this._deactivateAction( action );
  39751. this._removeInactiveAction( action );
  39752. }
  39753. }
  39754. }
  39755. /**
  39756. * Represents a 3D render target.
  39757. *
  39758. * @augments RenderTarget
  39759. */
  39760. class RenderTarget3D extends RenderTarget {
  39761. /**
  39762. * Constructs a new 3D render target.
  39763. *
  39764. * @param {number} [width=1] - The width of the render target.
  39765. * @param {number} [height=1] - The height of the render target.
  39766. * @param {number} [depth=1] - The height of the render target.
  39767. * @param {RenderTarget~Options} [options] - The configuration object.
  39768. */
  39769. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39770. super( width, height, options );
  39771. /**
  39772. * This flag can be used for type testing.
  39773. *
  39774. * @type {boolean}
  39775. * @readonly
  39776. * @default true
  39777. */
  39778. this.isRenderTarget3D = true;
  39779. this.depth = depth;
  39780. /**
  39781. * Overwritten with a different texture type.
  39782. *
  39783. * @type {Data3DTexture}
  39784. */
  39785. this.texture = new Data3DTexture( null, width, height, depth );
  39786. this._setTextureOptions( options );
  39787. this.texture.isRenderTargetTexture = true;
  39788. }
  39789. }
  39790. /**
  39791. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39792. *
  39793. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39794. * ```js
  39795. * uniforms: {
  39796. * time: { value: 1.0 },
  39797. * resolution: new Uniform( new Vector2() )
  39798. * };
  39799. * ```
  39800. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39801. * in {@link WebGLRenderer}.
  39802. */
  39803. class Uniform {
  39804. /**
  39805. * Constructs a new uniform.
  39806. *
  39807. * @param {any} value - The uniform value.
  39808. */
  39809. constructor( value ) {
  39810. /**
  39811. * The uniform value.
  39812. *
  39813. * @type {any}
  39814. */
  39815. this.value = value;
  39816. }
  39817. /**
  39818. * Returns a new uniform with copied values from this instance.
  39819. * If the value has a `clone()` method, the value is cloned as well.
  39820. *
  39821. * @return {Uniform} A clone of this instance.
  39822. */
  39823. clone() {
  39824. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39825. }
  39826. }
  39827. let _id$1 = 0;
  39828. /**
  39829. * A class for managing multiple uniforms in a single group. The renderer will process
  39830. * such a definition as a single UBO.
  39831. *
  39832. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39833. * in {@link WebGLRenderer}.
  39834. *
  39835. * @augments EventDispatcher
  39836. */
  39837. class UniformsGroup extends EventDispatcher {
  39838. /**
  39839. * Constructs a new uniforms group.
  39840. */
  39841. constructor() {
  39842. super();
  39843. /**
  39844. * This flag can be used for type testing.
  39845. *
  39846. * @type {boolean}
  39847. * @readonly
  39848. * @default true
  39849. */
  39850. this.isUniformsGroup = true;
  39851. /**
  39852. * The ID of the 3D object.
  39853. *
  39854. * @name UniformsGroup#id
  39855. * @type {number}
  39856. * @readonly
  39857. */
  39858. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39859. /**
  39860. * The name of the uniforms group.
  39861. *
  39862. * @type {string}
  39863. */
  39864. this.name = '';
  39865. /**
  39866. * The buffer usage.
  39867. *
  39868. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39869. * @default StaticDrawUsage
  39870. */
  39871. this.usage = StaticDrawUsage;
  39872. /**
  39873. * An array holding the uniforms.
  39874. *
  39875. * @type {Array<Uniform>}
  39876. */
  39877. this.uniforms = [];
  39878. }
  39879. /**
  39880. * Adds the given uniform to this uniforms group.
  39881. *
  39882. * @param {Uniform} uniform - The uniform to add.
  39883. * @return {UniformsGroup} A reference to this uniforms group.
  39884. */
  39885. add( uniform ) {
  39886. this.uniforms.push( uniform );
  39887. return this;
  39888. }
  39889. /**
  39890. * Removes the given uniform from this uniforms group.
  39891. *
  39892. * @param {Uniform} uniform - The uniform to remove.
  39893. * @return {UniformsGroup} A reference to this uniforms group.
  39894. */
  39895. remove( uniform ) {
  39896. const index = this.uniforms.indexOf( uniform );
  39897. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39898. return this;
  39899. }
  39900. /**
  39901. * Sets the name of this uniforms group.
  39902. *
  39903. * @param {string} name - The name to set.
  39904. * @return {UniformsGroup} A reference to this uniforms group.
  39905. */
  39906. setName( name ) {
  39907. this.name = name;
  39908. return this;
  39909. }
  39910. /**
  39911. * Sets the usage of this uniforms group.
  39912. *
  39913. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39914. * @return {UniformsGroup} A reference to this uniforms group.
  39915. */
  39916. setUsage( value ) {
  39917. this.usage = value;
  39918. return this;
  39919. }
  39920. /**
  39921. * Frees the GPU-related resources allocated by this instance. Call this
  39922. * method whenever this instance is no longer used in your app.
  39923. *
  39924. * @fires Texture#dispose
  39925. */
  39926. dispose() {
  39927. this.dispatchEvent( { type: 'dispose' } );
  39928. }
  39929. /**
  39930. * Copies the values of the given uniforms group to this instance.
  39931. *
  39932. * @param {UniformsGroup} source - The uniforms group to copy.
  39933. * @return {UniformsGroup} A reference to this uniforms group.
  39934. */
  39935. copy( source ) {
  39936. this.name = source.name;
  39937. this.usage = source.usage;
  39938. const uniformsSource = source.uniforms;
  39939. this.uniforms.length = 0;
  39940. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39941. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39942. for ( let j = 0; j < uniforms.length; j ++ ) {
  39943. this.uniforms.push( uniforms[ j ].clone() );
  39944. }
  39945. }
  39946. return this;
  39947. }
  39948. /**
  39949. * Returns a new uniforms group with copied values from this instance.
  39950. *
  39951. * @return {UniformsGroup} A clone of this instance.
  39952. */
  39953. clone() {
  39954. return new this.constructor().copy( this );
  39955. }
  39956. }
  39957. /**
  39958. * An instanced version of an interleaved buffer.
  39959. *
  39960. * @augments InterleavedBuffer
  39961. */
  39962. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39963. /**
  39964. * Constructs a new instanced interleaved buffer.
  39965. *
  39966. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39967. * @param {number} stride - The number of typed-array elements per vertex.
  39968. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39969. */
  39970. constructor( array, stride, meshPerAttribute = 1 ) {
  39971. super( array, stride );
  39972. /**
  39973. * This flag can be used for type testing.
  39974. *
  39975. * @type {boolean}
  39976. * @readonly
  39977. * @default true
  39978. */
  39979. this.isInstancedInterleavedBuffer = true;
  39980. /**
  39981. * Defines how often a value of this buffer attribute should be repeated,
  39982. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39983. *
  39984. * @type {number}
  39985. * @default 1
  39986. */
  39987. this.meshPerAttribute = meshPerAttribute;
  39988. }
  39989. copy( source ) {
  39990. super.copy( source );
  39991. this.meshPerAttribute = source.meshPerAttribute;
  39992. return this;
  39993. }
  39994. clone( data ) {
  39995. const ib = super.clone( data );
  39996. ib.meshPerAttribute = this.meshPerAttribute;
  39997. return ib;
  39998. }
  39999. toJSON( data ) {
  40000. const json = super.toJSON( data );
  40001. json.isInstancedInterleavedBuffer = true;
  40002. json.meshPerAttribute = this.meshPerAttribute;
  40003. return json;
  40004. }
  40005. }
  40006. /**
  40007. * An alternative version of a buffer attribute with more control over the VBO.
  40008. *
  40009. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40010. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40011. *
  40012. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40013. * or even produces the VBOs in question.
  40014. *
  40015. * Notice that this class can only be used with {@link WebGLRenderer}.
  40016. */
  40017. class GLBufferAttribute {
  40018. /**
  40019. * Constructs a new GL buffer attribute.
  40020. *
  40021. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40022. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40023. * @param {number} itemSize - The item size.
  40024. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40025. * @param {number} count - The expected number of vertices in VBO.
  40026. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40027. */
  40028. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40029. /**
  40030. * This flag can be used for type testing.
  40031. *
  40032. * @type {boolean}
  40033. * @readonly
  40034. * @default true
  40035. */
  40036. this.isGLBufferAttribute = true;
  40037. /**
  40038. * The name of the buffer attribute.
  40039. *
  40040. * @type {string}
  40041. */
  40042. this.name = '';
  40043. /**
  40044. * The native WebGL buffer.
  40045. *
  40046. * @type {WebGLBuffer}
  40047. */
  40048. this.buffer = buffer;
  40049. /**
  40050. * The native data type.
  40051. *
  40052. * @type {number}
  40053. */
  40054. this.type = type;
  40055. /**
  40056. * The item size, see {@link BufferAttribute#itemSize}.
  40057. *
  40058. * @type {number}
  40059. */
  40060. this.itemSize = itemSize;
  40061. /**
  40062. * The corresponding size (in bytes) for the given `type` parameter.
  40063. *
  40064. * @type {number}
  40065. */
  40066. this.elementSize = elementSize;
  40067. /**
  40068. * The expected number of vertices in VBO.
  40069. *
  40070. * @type {number}
  40071. */
  40072. this.count = count;
  40073. /**
  40074. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40075. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40076. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40077. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40078. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40079. *
  40080. * @type {boolean}
  40081. */
  40082. this.normalized = normalized;
  40083. /**
  40084. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40085. *
  40086. * @type {number}
  40087. */
  40088. this.version = 0;
  40089. }
  40090. /**
  40091. * Flag to indicate that this attribute has changed and should be re-sent to
  40092. * the GPU. Set this to `true` when you modify the value of the array.
  40093. *
  40094. * @type {number}
  40095. * @default false
  40096. * @param {boolean} value
  40097. */
  40098. set needsUpdate( value ) {
  40099. if ( value === true ) this.version ++;
  40100. }
  40101. /**
  40102. * Sets the given native WebGL buffer.
  40103. *
  40104. * @param {WebGLBuffer} buffer - The buffer to set.
  40105. * @return {BufferAttribute} A reference to this instance.
  40106. */
  40107. setBuffer( buffer ) {
  40108. this.buffer = buffer;
  40109. return this;
  40110. }
  40111. /**
  40112. * Sets the given native data type and element size.
  40113. *
  40114. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40115. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40116. * @return {BufferAttribute} A reference to this instance.
  40117. */
  40118. setType( type, elementSize ) {
  40119. this.type = type;
  40120. this.elementSize = elementSize;
  40121. return this;
  40122. }
  40123. /**
  40124. * Sets the item size.
  40125. *
  40126. * @param {number} itemSize - The item size.
  40127. * @return {BufferAttribute} A reference to this instance.
  40128. */
  40129. setItemSize( itemSize ) {
  40130. this.itemSize = itemSize;
  40131. return this;
  40132. }
  40133. /**
  40134. * Sets the count (the expected number of vertices in VBO).
  40135. *
  40136. * @param {number} count - The count.
  40137. * @return {BufferAttribute} A reference to this instance.
  40138. */
  40139. setCount( count ) {
  40140. this.count = count;
  40141. return this;
  40142. }
  40143. }
  40144. const _matrix = /*@__PURE__*/ new Matrix4();
  40145. /**
  40146. * This class is designed to assist with raycasting. Raycasting is used for
  40147. * mouse picking (working out what objects in the 3d space the mouse is over)
  40148. * amongst other things.
  40149. */
  40150. class Raycaster {
  40151. /**
  40152. * Constructs a new raycaster.
  40153. *
  40154. * @param {Vector3} origin - The origin vector where the ray casts from.
  40155. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40156. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40157. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40158. */
  40159. constructor( origin, direction, near = 0, far = Infinity ) {
  40160. /**
  40161. * The ray used for raycasting.
  40162. *
  40163. * @type {Ray}
  40164. */
  40165. this.ray = new Ray( origin, direction );
  40166. /**
  40167. * All results returned are further away than near. Near can't be negative.
  40168. *
  40169. * @type {number}
  40170. * @default 0
  40171. */
  40172. this.near = near;
  40173. /**
  40174. * All results returned are closer than far. Far can't be lower than near.
  40175. *
  40176. * @type {number}
  40177. * @default Infinity
  40178. */
  40179. this.far = far;
  40180. /**
  40181. * The camera to use when raycasting against view-dependent objects such as
  40182. * billboarded objects like sprites. This field can be set manually or
  40183. * is set when calling `setFromCamera()`.
  40184. *
  40185. * @type {?Camera}
  40186. * @default null
  40187. */
  40188. this.camera = null;
  40189. /**
  40190. * Allows to selectively ignore 3D objects when performing intersection tests.
  40191. * The following code example ensures that only 3D objects on layer `1` will be
  40192. * honored by raycaster.
  40193. * ```js
  40194. * raycaster.layers.set( 1 );
  40195. * object.layers.enable( 1 );
  40196. * ```
  40197. *
  40198. * @type {Layers}
  40199. */
  40200. this.layers = new Layers();
  40201. /**
  40202. * A parameter object that configures the raycasting. It has the structure:
  40203. *
  40204. * ```
  40205. * {
  40206. * Mesh: {},
  40207. * Line: { threshold: 1 },
  40208. * LOD: {},
  40209. * Points: { threshold: 1 },
  40210. * Sprite: {}
  40211. * }
  40212. * ```
  40213. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40214. *
  40215. * @type {Object}
  40216. */
  40217. this.params = {
  40218. Mesh: {},
  40219. Line: { threshold: 1 },
  40220. LOD: {},
  40221. Points: { threshold: 1 },
  40222. Sprite: {}
  40223. };
  40224. }
  40225. /**
  40226. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40227. *
  40228. * @param {Vector3} origin - The origin vector where the ray casts from.
  40229. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40230. */
  40231. set( origin, direction ) {
  40232. // direction is assumed to be normalized (for accurate distance calculations)
  40233. this.ray.set( origin, direction );
  40234. }
  40235. /**
  40236. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40237. *
  40238. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40239. * X and Y components should be between `-1` and `1`.
  40240. * @param {Camera} camera - The camera from which the ray should originate.
  40241. */
  40242. setFromCamera( coords, camera ) {
  40243. if ( camera.isPerspectiveCamera ) {
  40244. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40245. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40246. this.camera = camera;
  40247. } else if ( camera.isOrthographicCamera ) {
  40248. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40249. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40250. this.camera = camera;
  40251. } else {
  40252. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40253. }
  40254. }
  40255. /**
  40256. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40257. *
  40258. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40259. * @return {Raycaster} A reference to this raycaster.
  40260. */
  40261. setFromXRController( controller ) {
  40262. _matrix.identity().extractRotation( controller.matrixWorld );
  40263. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40264. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40265. return this;
  40266. }
  40267. /**
  40268. * The intersection point of a raycaster intersection test.
  40269. * @typedef {Object} Raycaster~Intersection
  40270. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40271. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40272. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40273. * @property {Vector3} point - The intersection point, in world coordinates.
  40274. * @property {Object} face - The face that has been intersected.
  40275. * @property {number} faceIndex - The face index.
  40276. * @property {Object3D} object - The 3D object that has been intersected.
  40277. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40278. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40279. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40280. * @property {number} instanceId - The index number of the instance where the ray
  40281. * intersects the {@link InstancedMesh}.
  40282. */
  40283. /**
  40284. * Checks all intersection between the ray and the object with or without the
  40285. * descendants. Intersections are returned sorted by distance, closest first.
  40286. *
  40287. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40288. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40289. * differently to ray casting than lines or points.
  40290. *
  40291. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40292. * to be detected; intersections of the ray passing through the back of a face will not
  40293. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40294. * to `THREE.DoubleSide`.
  40295. *
  40296. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40297. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40298. * Otherwise it only checks intersection with the object.
  40299. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40300. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40301. */
  40302. intersectObject( object, recursive = true, intersects = [] ) {
  40303. intersect( object, this, intersects, recursive );
  40304. intersects.sort( ascSort );
  40305. return intersects;
  40306. }
  40307. /**
  40308. * Checks all intersection between the ray and the objects with or without
  40309. * the descendants. Intersections are returned sorted by distance, closest first.
  40310. *
  40311. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40312. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40313. * Otherwise it only checks intersection with the object.
  40314. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40315. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40316. */
  40317. intersectObjects( objects, recursive = true, intersects = [] ) {
  40318. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40319. intersect( objects[ i ], this, intersects, recursive );
  40320. }
  40321. intersects.sort( ascSort );
  40322. return intersects;
  40323. }
  40324. }
  40325. function ascSort( a, b ) {
  40326. return a.distance - b.distance;
  40327. }
  40328. function intersect( object, raycaster, intersects, recursive ) {
  40329. let propagate = true;
  40330. if ( object.layers.test( raycaster.layers ) ) {
  40331. const result = object.raycast( raycaster, intersects );
  40332. if ( result === false ) propagate = false;
  40333. }
  40334. if ( propagate === true && recursive === true ) {
  40335. const children = object.children;
  40336. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40337. intersect( children[ i ], raycaster, intersects, true );
  40338. }
  40339. }
  40340. }
  40341. /**
  40342. * This class is an alternative to {@link Clock} with a different API design and behavior.
  40343. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  40344. *
  40345. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  40346. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  40347. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  40348. * is inactive (e.g. tab switched or browser hidden).
  40349. *
  40350. * ```js
  40351. * const timer = new Timer();
  40352. * timer.connect( document ); // use Page Visibility API
  40353. * ```
  40354. */
  40355. class Timer {
  40356. /**
  40357. * Constructs a new timer.
  40358. */
  40359. constructor() {
  40360. this._previousTime = 0;
  40361. this._currentTime = 0;
  40362. this._startTime = performance.now();
  40363. this._delta = 0;
  40364. this._elapsed = 0;
  40365. this._timescale = 1;
  40366. this._document = null;
  40367. this._pageVisibilityHandler = null;
  40368. }
  40369. /**
  40370. * Connect the timer to the given document.Calling this method is not mandatory to
  40371. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40372. * delta values.
  40373. *
  40374. * @param {Document} document - The document.
  40375. */
  40376. connect( document ) {
  40377. this._document = document;
  40378. // use Page Visibility API to avoid large time delta values
  40379. if ( document.hidden !== undefined ) {
  40380. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40381. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40382. }
  40383. }
  40384. /**
  40385. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40386. */
  40387. disconnect() {
  40388. if ( this._pageVisibilityHandler !== null ) {
  40389. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40390. this._pageVisibilityHandler = null;
  40391. }
  40392. this._document = null;
  40393. }
  40394. /**
  40395. * Returns the time delta in seconds.
  40396. *
  40397. * @return {number} The time delta in second.
  40398. */
  40399. getDelta() {
  40400. return this._delta / 1000;
  40401. }
  40402. /**
  40403. * Returns the elapsed time in seconds.
  40404. *
  40405. * @return {number} The elapsed time in second.
  40406. */
  40407. getElapsed() {
  40408. return this._elapsed / 1000;
  40409. }
  40410. /**
  40411. * Returns the timescale.
  40412. *
  40413. * @return {number} The timescale.
  40414. */
  40415. getTimescale() {
  40416. return this._timescale;
  40417. }
  40418. /**
  40419. * Sets the given timescale which scale the time delta computation
  40420. * in `update()`.
  40421. *
  40422. * @param {number} timescale - The timescale to set.
  40423. * @return {Timer} A reference to this timer.
  40424. */
  40425. setTimescale( timescale ) {
  40426. this._timescale = timescale;
  40427. return this;
  40428. }
  40429. /**
  40430. * Resets the time computation for the current simulation step.
  40431. *
  40432. * @return {Timer} A reference to this timer.
  40433. */
  40434. reset() {
  40435. this._currentTime = performance.now() - this._startTime;
  40436. return this;
  40437. }
  40438. /**
  40439. * Can be used to free all internal resources. Usually called when
  40440. * the timer instance isn't required anymore.
  40441. */
  40442. dispose() {
  40443. this.disconnect();
  40444. }
  40445. /**
  40446. * Updates the internal state of the timer. This method should be called
  40447. * once per simulation step and before you perform queries against the timer
  40448. * (e.g. via `getDelta()`).
  40449. *
  40450. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40451. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40452. * time will be determined with `performance.now`.
  40453. * @return {Timer} A reference to this timer.
  40454. */
  40455. update( timestamp ) {
  40456. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40457. this._delta = 0;
  40458. } else {
  40459. this._previousTime = this._currentTime;
  40460. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40461. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40462. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40463. }
  40464. return this;
  40465. }
  40466. }
  40467. function handleVisibilityChange() {
  40468. if ( this._document.hidden === false ) this.reset();
  40469. }
  40470. /**
  40471. * This class can be used to represent points in 3D space as
  40472. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40473. */
  40474. class Spherical {
  40475. /**
  40476. * Constructs a new spherical.
  40477. *
  40478. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40479. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40480. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40481. */
  40482. constructor( radius = 1, phi = 0, theta = 0 ) {
  40483. /**
  40484. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40485. *
  40486. * @type {number}
  40487. * @default 1
  40488. */
  40489. this.radius = radius;
  40490. /**
  40491. * The polar angle in radians from the y (up) axis.
  40492. *
  40493. * @type {number}
  40494. * @default 0
  40495. */
  40496. this.phi = phi;
  40497. /**
  40498. * The equator/azimuthal angle in radians around the y (up) axis.
  40499. *
  40500. * @type {number}
  40501. * @default 0
  40502. */
  40503. this.theta = theta;
  40504. }
  40505. /**
  40506. * Sets the spherical components by copying the given values.
  40507. *
  40508. * @param {number} radius - The radius.
  40509. * @param {number} phi - The polar angle.
  40510. * @param {number} theta - The azimuthal angle.
  40511. * @return {Spherical} A reference to this spherical.
  40512. */
  40513. set( radius, phi, theta ) {
  40514. this.radius = radius;
  40515. this.phi = phi;
  40516. this.theta = theta;
  40517. return this;
  40518. }
  40519. /**
  40520. * Copies the values of the given spherical to this instance.
  40521. *
  40522. * @param {Spherical} other - The spherical to copy.
  40523. * @return {Spherical} A reference to this spherical.
  40524. */
  40525. copy( other ) {
  40526. this.radius = other.radius;
  40527. this.phi = other.phi;
  40528. this.theta = other.theta;
  40529. return this;
  40530. }
  40531. /**
  40532. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40533. * `0.000001`.
  40534. *
  40535. * @return {Spherical} A reference to this spherical.
  40536. */
  40537. makeSafe() {
  40538. const EPS = 0.000001;
  40539. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40540. return this;
  40541. }
  40542. /**
  40543. * Sets the spherical components from the given vector which is assumed to hold
  40544. * Cartesian coordinates.
  40545. *
  40546. * @param {Vector3} v - The vector to set.
  40547. * @return {Spherical} A reference to this spherical.
  40548. */
  40549. setFromVector3( v ) {
  40550. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40551. }
  40552. /**
  40553. * Sets the spherical components from the given Cartesian coordinates.
  40554. *
  40555. * @param {number} x - The x value.
  40556. * @param {number} y - The y value.
  40557. * @param {number} z - The z value.
  40558. * @return {Spherical} A reference to this spherical.
  40559. */
  40560. setFromCartesianCoords( x, y, z ) {
  40561. this.radius = Math.sqrt( x * x + y * y + z * z );
  40562. if ( this.radius === 0 ) {
  40563. this.theta = 0;
  40564. this.phi = 0;
  40565. } else {
  40566. this.theta = Math.atan2( x, z );
  40567. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40568. }
  40569. return this;
  40570. }
  40571. /**
  40572. * Returns a new spherical with copied values from this instance.
  40573. *
  40574. * @return {Spherical} A clone of this instance.
  40575. */
  40576. clone() {
  40577. return new this.constructor().copy( this );
  40578. }
  40579. }
  40580. /**
  40581. * This class can be used to represent points in 3D space as
  40582. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40583. */
  40584. class Cylindrical {
  40585. /**
  40586. * Constructs a new cylindrical.
  40587. *
  40588. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40589. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40590. * @param {number} [y=0] - The height above the x-z plane.
  40591. */
  40592. constructor( radius = 1, theta = 0, y = 0 ) {
  40593. /**
  40594. * The distance from the origin to a point in the x-z plane.
  40595. *
  40596. * @type {number}
  40597. * @default 1
  40598. */
  40599. this.radius = radius;
  40600. /**
  40601. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40602. *
  40603. * @type {number}
  40604. * @default 0
  40605. */
  40606. this.theta = theta;
  40607. /**
  40608. * The height above the x-z plane.
  40609. *
  40610. * @type {number}
  40611. * @default 0
  40612. */
  40613. this.y = y;
  40614. }
  40615. /**
  40616. * Sets the cylindrical components by copying the given values.
  40617. *
  40618. * @param {number} radius - The radius.
  40619. * @param {number} theta - The theta angle.
  40620. * @param {number} y - The height value.
  40621. * @return {Cylindrical} A reference to this cylindrical.
  40622. */
  40623. set( radius, theta, y ) {
  40624. this.radius = radius;
  40625. this.theta = theta;
  40626. this.y = y;
  40627. return this;
  40628. }
  40629. /**
  40630. * Copies the values of the given cylindrical to this instance.
  40631. *
  40632. * @param {Cylindrical} other - The cylindrical to copy.
  40633. * @return {Cylindrical} A reference to this cylindrical.
  40634. */
  40635. copy( other ) {
  40636. this.radius = other.radius;
  40637. this.theta = other.theta;
  40638. this.y = other.y;
  40639. return this;
  40640. }
  40641. /**
  40642. * Sets the cylindrical components from the given vector which is assumed to hold
  40643. * Cartesian coordinates.
  40644. *
  40645. * @param {Vector3} v - The vector to set.
  40646. * @return {Cylindrical} A reference to this cylindrical.
  40647. */
  40648. setFromVector3( v ) {
  40649. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40650. }
  40651. /**
  40652. * Sets the cylindrical components from the given Cartesian coordinates.
  40653. *
  40654. * @param {number} x - The x value.
  40655. * @param {number} y - The x value.
  40656. * @param {number} z - The x value.
  40657. * @return {Cylindrical} A reference to this cylindrical.
  40658. */
  40659. setFromCartesianCoords( x, y, z ) {
  40660. this.radius = Math.sqrt( x * x + z * z );
  40661. this.theta = Math.atan2( x, z );
  40662. this.y = y;
  40663. return this;
  40664. }
  40665. /**
  40666. * Returns a new cylindrical with copied values from this instance.
  40667. *
  40668. * @return {Cylindrical} A clone of this instance.
  40669. */
  40670. clone() {
  40671. return new this.constructor().copy( this );
  40672. }
  40673. }
  40674. /**
  40675. * Represents a 2x2 matrix.
  40676. *
  40677. * A Note on Row-Major and Column-Major Ordering:
  40678. *
  40679. * The constructor and {@link Matrix2#set} method take arguments in
  40680. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40681. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40682. * This means that calling:
  40683. * ```js
  40684. * const m = new THREE.Matrix2();
  40685. * m.set( 11, 12,
  40686. * 21, 22 );
  40687. * ```
  40688. * will result in the elements array containing:
  40689. * ```js
  40690. * m.elements = [ 11, 21,
  40691. * 12, 22 ];
  40692. * ```
  40693. * and internally all calculations are performed using column-major ordering.
  40694. * However, as the actual ordering makes no difference mathematically and
  40695. * most people are used to thinking about matrices in row-major order, the
  40696. * three.js documentation shows matrices in row-major order. Just bear in
  40697. * mind that if you are reading the source code, you'll have to take the
  40698. * transpose of any matrices outlined here to make sense of the calculations.
  40699. */
  40700. class Matrix2 {
  40701. /**
  40702. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40703. * in row-major order. If no arguments are provided, the constructor
  40704. * initializes the matrix as an identity matrix.
  40705. *
  40706. * @param {number} [n11] - 1-1 matrix element.
  40707. * @param {number} [n12] - 1-2 matrix element.
  40708. * @param {number} [n21] - 2-1 matrix element.
  40709. * @param {number} [n22] - 2-2 matrix element.
  40710. */
  40711. constructor( n11, n12, n21, n22 ) {
  40712. /**
  40713. * This flag can be used for type testing.
  40714. *
  40715. * @type {boolean}
  40716. * @readonly
  40717. * @default true
  40718. */
  40719. Matrix2.prototype.isMatrix2 = true;
  40720. /**
  40721. * A column-major list of matrix values.
  40722. *
  40723. * @type {Array<number>}
  40724. */
  40725. this.elements = [
  40726. 1, 0,
  40727. 0, 1,
  40728. ];
  40729. if ( n11 !== undefined ) {
  40730. this.set( n11, n12, n21, n22 );
  40731. }
  40732. }
  40733. /**
  40734. * Sets this matrix to the 2x2 identity matrix.
  40735. *
  40736. * @return {Matrix2} A reference to this matrix.
  40737. */
  40738. identity() {
  40739. this.set(
  40740. 1, 0,
  40741. 0, 1,
  40742. );
  40743. return this;
  40744. }
  40745. /**
  40746. * Sets the elements of the matrix from the given array.
  40747. *
  40748. * @param {Array<number>} array - The matrix elements in column-major order.
  40749. * @param {number} [offset=0] - Index of the first element in the array.
  40750. * @return {Matrix2} A reference to this matrix.
  40751. */
  40752. fromArray( array, offset = 0 ) {
  40753. for ( let i = 0; i < 4; i ++ ) {
  40754. this.elements[ i ] = array[ i + offset ];
  40755. }
  40756. return this;
  40757. }
  40758. /**
  40759. * Sets the elements of the matrix.The arguments are supposed to be
  40760. * in row-major order.
  40761. *
  40762. * @param {number} n11 - 1-1 matrix element.
  40763. * @param {number} n12 - 1-2 matrix element.
  40764. * @param {number} n21 - 2-1 matrix element.
  40765. * @param {number} n22 - 2-2 matrix element.
  40766. * @return {Matrix2} A reference to this matrix.
  40767. */
  40768. set( n11, n12, n21, n22 ) {
  40769. const te = this.elements;
  40770. te[ 0 ] = n11; te[ 2 ] = n12;
  40771. te[ 1 ] = n21; te[ 3 ] = n22;
  40772. return this;
  40773. }
  40774. }
  40775. const _vector$4 = /*@__PURE__*/ new Vector2();
  40776. /**
  40777. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40778. */
  40779. class Box2 {
  40780. /**
  40781. * Constructs a new bounding box.
  40782. *
  40783. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40784. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40785. */
  40786. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40787. /**
  40788. * This flag can be used for type testing.
  40789. *
  40790. * @type {boolean}
  40791. * @readonly
  40792. * @default true
  40793. */
  40794. this.isBox2 = true;
  40795. /**
  40796. * The lower boundary of the box.
  40797. *
  40798. * @type {Vector2}
  40799. */
  40800. this.min = min;
  40801. /**
  40802. * The upper boundary of the box.
  40803. *
  40804. * @type {Vector2}
  40805. */
  40806. this.max = max;
  40807. }
  40808. /**
  40809. * Sets the lower and upper boundaries of this box.
  40810. * Please note that this method only copies the values from the given objects.
  40811. *
  40812. * @param {Vector2} min - The lower boundary of the box.
  40813. * @param {Vector2} max - The upper boundary of the box.
  40814. * @return {Box2} A reference to this bounding box.
  40815. */
  40816. set( min, max ) {
  40817. this.min.copy( min );
  40818. this.max.copy( max );
  40819. return this;
  40820. }
  40821. /**
  40822. * Sets the upper and lower bounds of this box so it encloses the position data
  40823. * in the given array.
  40824. *
  40825. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40826. * @return {Box2} A reference to this bounding box.
  40827. */
  40828. setFromPoints( points ) {
  40829. this.makeEmpty();
  40830. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40831. this.expandByPoint( points[ i ] );
  40832. }
  40833. return this;
  40834. }
  40835. /**
  40836. * Centers this box on the given center vector and sets this box's width, height and
  40837. * depth to the given size values.
  40838. *
  40839. * @param {Vector2} center - The center of the box.
  40840. * @param {Vector2} size - The x and y dimensions of the box.
  40841. * @return {Box2} A reference to this bounding box.
  40842. */
  40843. setFromCenterAndSize( center, size ) {
  40844. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40845. this.min.copy( center ).sub( halfSize );
  40846. this.max.copy( center ).add( halfSize );
  40847. return this;
  40848. }
  40849. /**
  40850. * Returns a new box with copied values from this instance.
  40851. *
  40852. * @return {Box2} A clone of this instance.
  40853. */
  40854. clone() {
  40855. return new this.constructor().copy( this );
  40856. }
  40857. /**
  40858. * Copies the values of the given box to this instance.
  40859. *
  40860. * @param {Box2} box - The box to copy.
  40861. * @return {Box2} A reference to this bounding box.
  40862. */
  40863. copy( box ) {
  40864. this.min.copy( box.min );
  40865. this.max.copy( box.max );
  40866. return this;
  40867. }
  40868. /**
  40869. * Makes this box empty which means in encloses a zero space in 2D.
  40870. *
  40871. * @return {Box2} A reference to this bounding box.
  40872. */
  40873. makeEmpty() {
  40874. this.min.x = this.min.y = + Infinity;
  40875. this.max.x = this.max.y = - Infinity;
  40876. return this;
  40877. }
  40878. /**
  40879. * Returns true if this box includes zero points within its bounds.
  40880. * Note that a box with equal lower and upper bounds still includes one
  40881. * point, the one both bounds share.
  40882. *
  40883. * @return {boolean} Whether this box is empty or not.
  40884. */
  40885. isEmpty() {
  40886. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40887. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40888. }
  40889. /**
  40890. * Returns the center point of this box.
  40891. *
  40892. * @param {Vector2} target - The target vector that is used to store the method's result.
  40893. * @return {Vector2} The center point.
  40894. */
  40895. getCenter( target ) {
  40896. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40897. }
  40898. /**
  40899. * Returns the dimensions of this box.
  40900. *
  40901. * @param {Vector2} target - The target vector that is used to store the method's result.
  40902. * @return {Vector2} The size.
  40903. */
  40904. getSize( target ) {
  40905. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40906. }
  40907. /**
  40908. * Expands the boundaries of this box to include the given point.
  40909. *
  40910. * @param {Vector2} point - The point that should be included by the bounding box.
  40911. * @return {Box2} A reference to this bounding box.
  40912. */
  40913. expandByPoint( point ) {
  40914. this.min.min( point );
  40915. this.max.max( point );
  40916. return this;
  40917. }
  40918. /**
  40919. * Expands this box equilaterally by the given vector. The width of this
  40920. * box will be expanded by the x component of the vector in both
  40921. * directions. The height of this box will be expanded by the y component of
  40922. * the vector in both directions.
  40923. *
  40924. * @param {Vector2} vector - The vector that should expand the bounding box.
  40925. * @return {Box2} A reference to this bounding box.
  40926. */
  40927. expandByVector( vector ) {
  40928. this.min.sub( vector );
  40929. this.max.add( vector );
  40930. return this;
  40931. }
  40932. /**
  40933. * Expands each dimension of the box by the given scalar. If negative, the
  40934. * dimensions of the box will be contracted.
  40935. *
  40936. * @param {number} scalar - The scalar value that should expand the bounding box.
  40937. * @return {Box2} A reference to this bounding box.
  40938. */
  40939. expandByScalar( scalar ) {
  40940. this.min.addScalar( - scalar );
  40941. this.max.addScalar( scalar );
  40942. return this;
  40943. }
  40944. /**
  40945. * Returns `true` if the given point lies within or on the boundaries of this box.
  40946. *
  40947. * @param {Vector2} point - The point to test.
  40948. * @return {boolean} Whether the bounding box contains the given point or not.
  40949. */
  40950. containsPoint( point ) {
  40951. return point.x >= this.min.x && point.x <= this.max.x &&
  40952. point.y >= this.min.y && point.y <= this.max.y;
  40953. }
  40954. /**
  40955. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40956. * If this box and the given one are identical, this function also returns `true`.
  40957. *
  40958. * @param {Box2} box - The bounding box to test.
  40959. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40960. */
  40961. containsBox( box ) {
  40962. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40963. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40964. }
  40965. /**
  40966. * Returns a point as a proportion of this box's width and height.
  40967. *
  40968. * @param {Vector2} point - A point in 2D space.
  40969. * @param {Vector2} target - The target vector that is used to store the method's result.
  40970. * @return {Vector2} A point as a proportion of this box's width and height.
  40971. */
  40972. getParameter( point, target ) {
  40973. // This can potentially have a divide by zero if the box
  40974. // has a size dimension of 0.
  40975. return target.set(
  40976. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40977. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40978. );
  40979. }
  40980. /**
  40981. * Returns `true` if the given bounding box intersects with this bounding box.
  40982. *
  40983. * @param {Box2} box - The bounding box to test.
  40984. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40985. */
  40986. intersectsBox( box ) {
  40987. // using 4 splitting planes to rule out intersections
  40988. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40989. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40990. }
  40991. /**
  40992. * Clamps the given point within the bounds of this box.
  40993. *
  40994. * @param {Vector2} point - The point to clamp.
  40995. * @param {Vector2} target - The target vector that is used to store the method's result.
  40996. * @return {Vector2} The clamped point.
  40997. */
  40998. clampPoint( point, target ) {
  40999. return target.copy( point ).clamp( this.min, this.max );
  41000. }
  41001. /**
  41002. * Returns the euclidean distance from any edge of this box to the specified point. If
  41003. * the given point lies inside of this box, the distance will be `0`.
  41004. *
  41005. * @param {Vector2} point - The point to compute the distance to.
  41006. * @return {number} The euclidean distance.
  41007. */
  41008. distanceToPoint( point ) {
  41009. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41010. }
  41011. /**
  41012. * Computes the intersection of this bounding box and the given one, setting the upper
  41013. * bound of this box to the lesser of the two boxes' upper bounds and the
  41014. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41015. * there's no overlap, makes this box empty.
  41016. *
  41017. * @param {Box2} box - The bounding box to intersect with.
  41018. * @return {Box2} A reference to this bounding box.
  41019. */
  41020. intersect( box ) {
  41021. this.min.max( box.min );
  41022. this.max.min( box.max );
  41023. if ( this.isEmpty() ) this.makeEmpty();
  41024. return this;
  41025. }
  41026. /**
  41027. * Computes the union of this box and another and the given one, setting the upper
  41028. * bound of this box to the greater of the two boxes' upper bounds and the
  41029. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41030. *
  41031. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41032. * @return {Box2} A reference to this bounding box.
  41033. */
  41034. union( box ) {
  41035. this.min.min( box.min );
  41036. this.max.max( box.max );
  41037. return this;
  41038. }
  41039. /**
  41040. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41041. * effectively moving it in 2D space.
  41042. *
  41043. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41044. * @return {Box2} A reference to this bounding box.
  41045. */
  41046. translate( offset ) {
  41047. this.min.add( offset );
  41048. this.max.add( offset );
  41049. return this;
  41050. }
  41051. /**
  41052. * Returns `true` if this bounding box is equal with the given one.
  41053. *
  41054. * @param {Box2} box - The box to test for equality.
  41055. * @return {boolean} Whether this bounding box is equal with the given one.
  41056. */
  41057. equals( box ) {
  41058. return box.min.equals( this.min ) && box.max.equals( this.max );
  41059. }
  41060. }
  41061. const _startP = /*@__PURE__*/ new Vector3();
  41062. const _startEnd = /*@__PURE__*/ new Vector3();
  41063. const _d1 = /*@__PURE__*/ new Vector3();
  41064. const _d2 = /*@__PURE__*/ new Vector3();
  41065. const _r = /*@__PURE__*/ new Vector3();
  41066. const _c1 = /*@__PURE__*/ new Vector3();
  41067. const _c2 = /*@__PURE__*/ new Vector3();
  41068. /**
  41069. * An analytical line segment in 3D space represented by a start and end point.
  41070. */
  41071. class Line3 {
  41072. /**
  41073. * Constructs a new line segment.
  41074. *
  41075. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41076. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41077. */
  41078. constructor( start = new Vector3(), end = new Vector3() ) {
  41079. /**
  41080. * Start of the line segment.
  41081. *
  41082. * @type {Vector3}
  41083. */
  41084. this.start = start;
  41085. /**
  41086. * End of the line segment.
  41087. *
  41088. * @type {Vector3}
  41089. */
  41090. this.end = end;
  41091. }
  41092. /**
  41093. * Sets the start and end values by copying the given vectors.
  41094. *
  41095. * @param {Vector3} start - The start point.
  41096. * @param {Vector3} end - The end point.
  41097. * @return {Line3} A reference to this line segment.
  41098. */
  41099. set( start, end ) {
  41100. this.start.copy( start );
  41101. this.end.copy( end );
  41102. return this;
  41103. }
  41104. /**
  41105. * Copies the values of the given line segment to this instance.
  41106. *
  41107. * @param {Line3} line - The line segment to copy.
  41108. * @return {Line3} A reference to this line segment.
  41109. */
  41110. copy( line ) {
  41111. this.start.copy( line.start );
  41112. this.end.copy( line.end );
  41113. return this;
  41114. }
  41115. /**
  41116. * Returns the center of the line segment.
  41117. *
  41118. * @param {Vector3} target - The target vector that is used to store the method's result.
  41119. * @return {Vector3} The center point.
  41120. */
  41121. getCenter( target ) {
  41122. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41123. }
  41124. /**
  41125. * Returns the delta vector of the line segment's start and end point.
  41126. *
  41127. * @param {Vector3} target - The target vector that is used to store the method's result.
  41128. * @return {Vector3} The delta vector.
  41129. */
  41130. delta( target ) {
  41131. return target.subVectors( this.end, this.start );
  41132. }
  41133. /**
  41134. * Returns the squared Euclidean distance between the line' start and end point.
  41135. *
  41136. * @return {number} The squared Euclidean distance.
  41137. */
  41138. distanceSq() {
  41139. return this.start.distanceToSquared( this.end );
  41140. }
  41141. /**
  41142. * Returns the Euclidean distance between the line' start and end point.
  41143. *
  41144. * @return {number} The Euclidean distance.
  41145. */
  41146. distance() {
  41147. return this.start.distanceTo( this.end );
  41148. }
  41149. /**
  41150. * Returns a vector at a certain position along the line segment.
  41151. *
  41152. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41153. * @param {Vector3} target - The target vector that is used to store the method's result.
  41154. * @return {Vector3} The delta vector.
  41155. */
  41156. at( t, target ) {
  41157. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41158. }
  41159. /**
  41160. * Returns a point parameter based on the closest point as projected on the line segment.
  41161. *
  41162. * @param {Vector3} point - The point for which to return a point parameter.
  41163. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41164. * @return {number} The point parameter.
  41165. */
  41166. closestPointToPointParameter( point, clampToLine ) {
  41167. _startP.subVectors( point, this.start );
  41168. _startEnd.subVectors( this.end, this.start );
  41169. const startEnd2 = _startEnd.dot( _startEnd );
  41170. const startEnd_startP = _startEnd.dot( _startP );
  41171. let t = startEnd_startP / startEnd2;
  41172. if ( clampToLine ) {
  41173. t = clamp( t, 0, 1 );
  41174. }
  41175. return t;
  41176. }
  41177. /**
  41178. * Returns the closest point on the line for a given point.
  41179. *
  41180. * @param {Vector3} point - The point to compute the closest point on the line for.
  41181. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41182. * @param {Vector3} target - The target vector that is used to store the method's result.
  41183. * @return {Vector3} The closest point on the line.
  41184. */
  41185. closestPointToPoint( point, clampToLine, target ) {
  41186. const t = this.closestPointToPointParameter( point, clampToLine );
  41187. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41188. }
  41189. /**
  41190. * Returns the closest squared distance between this line segment and the given one.
  41191. *
  41192. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41193. * @param {Vector3} [c1] - The closest point on this line segment.
  41194. * @param {Vector3} [c2] - The closest point on the given line segment.
  41195. * @return {number} The squared distance between this line segment and the given one.
  41196. */
  41197. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41198. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41199. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41200. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41201. // distance between between S1(s) and S2(t)
  41202. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41203. let s, t;
  41204. const p1 = this.start;
  41205. const p2 = line.start;
  41206. const q1 = this.end;
  41207. const q2 = line.end;
  41208. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41209. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41210. _r.subVectors( p1, p2 );
  41211. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41212. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41213. const f = _d2.dot( _r );
  41214. // Check if either or both segments degenerate into points
  41215. if ( a <= EPSILON && e <= EPSILON ) {
  41216. // Both segments degenerate into points
  41217. c1.copy( p1 );
  41218. c2.copy( p2 );
  41219. c1.sub( c2 );
  41220. return c1.dot( c1 );
  41221. }
  41222. if ( a <= EPSILON ) {
  41223. // First segment degenerates into a point
  41224. s = 0;
  41225. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41226. t = clamp( t, 0, 1 );
  41227. } else {
  41228. const c = _d1.dot( _r );
  41229. if ( e <= EPSILON ) {
  41230. // Second segment degenerates into a point
  41231. t = 0;
  41232. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41233. } else {
  41234. // The general nondegenerate case starts here
  41235. const b = _d1.dot( _d2 );
  41236. const denom = a * e - b * b; // Always nonnegative
  41237. // If segments not parallel, compute closest point on L1 to L2 and
  41238. // clamp to segment S1. Else pick arbitrary s (here 0)
  41239. if ( denom !== 0 ) {
  41240. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41241. } else {
  41242. s = 0;
  41243. }
  41244. // Compute point on L2 closest to S1(s) using
  41245. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41246. t = ( b * s + f ) / e;
  41247. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41248. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41249. // and clamp s to [0, 1]
  41250. if ( t < 0 ) {
  41251. t = 0.;
  41252. s = clamp( - c / a, 0, 1 );
  41253. } else if ( t > 1 ) {
  41254. t = 1;
  41255. s = clamp( ( b - c ) / a, 0, 1 );
  41256. }
  41257. }
  41258. }
  41259. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  41260. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  41261. c1.sub( c2 );
  41262. return c1.dot( c1 );
  41263. }
  41264. /**
  41265. * Applies a 4x4 transformation matrix to this line segment.
  41266. *
  41267. * @param {Matrix4} matrix - The transformation matrix.
  41268. * @return {Line3} A reference to this line segment.
  41269. */
  41270. applyMatrix4( matrix ) {
  41271. this.start.applyMatrix4( matrix );
  41272. this.end.applyMatrix4( matrix );
  41273. return this;
  41274. }
  41275. /**
  41276. * Returns `true` if this line segment is equal with the given one.
  41277. *
  41278. * @param {Line3} line - The line segment to test for equality.
  41279. * @return {boolean} Whether this line segment is equal with the given one.
  41280. */
  41281. equals( line ) {
  41282. return line.start.equals( this.start ) && line.end.equals( this.end );
  41283. }
  41284. /**
  41285. * Returns a new line segment with copied values from this instance.
  41286. *
  41287. * @return {Line3} A clone of this instance.
  41288. */
  41289. clone() {
  41290. return new this.constructor().copy( this );
  41291. }
  41292. }
  41293. const _vector$3 = /*@__PURE__*/ new Vector3();
  41294. /**
  41295. * This displays a cone shaped helper object for a {@link SpotLight}.
  41296. *
  41297. * When the spot light or its target are transformed or light properties are
  41298. * changed, it's necessary to call the `update()` method of the respective helper.
  41299. *
  41300. * ```js
  41301. * const spotLight = new THREE.SpotLight( 0xffffff );
  41302. * spotLight.position.set( 10, 10, 10 );
  41303. * scene.add( spotLight );
  41304. *
  41305. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41306. * scene.add( spotLightHelper );
  41307. * ```
  41308. *
  41309. * @augments Object3D
  41310. */
  41311. class SpotLightHelper extends Object3D {
  41312. /**
  41313. * Constructs a new spot light helper.
  41314. *
  41315. * @param {HemisphereLight} light - The light to be visualized.
  41316. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41317. * the color of the light.
  41318. */
  41319. constructor( light, color ) {
  41320. super();
  41321. /**
  41322. * The light being visualized.
  41323. *
  41324. * @type {SpotLight}
  41325. */
  41326. this.light = light;
  41327. this.matrixAutoUpdate = false;
  41328. /**
  41329. * The color parameter passed in the constructor.
  41330. * If not set, the helper will take the color of the light.
  41331. *
  41332. * @type {number|Color|string}
  41333. */
  41334. this.color = color;
  41335. this.type = 'SpotLightHelper';
  41336. const geometry = new BufferGeometry();
  41337. const positions = [
  41338. 0, 0, 0, 0, 0, 1,
  41339. 0, 0, 0, 1, 0, 1,
  41340. 0, 0, 0, -1, 0, 1,
  41341. 0, 0, 0, 0, 1, 1,
  41342. 0, 0, 0, 0, -1, 1
  41343. ];
  41344. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41345. const p1 = ( i / l ) * Math.PI * 2;
  41346. const p2 = ( j / l ) * Math.PI * 2;
  41347. positions.push(
  41348. Math.cos( p1 ), Math.sin( p1 ), 1,
  41349. Math.cos( p2 ), Math.sin( p2 ), 1
  41350. );
  41351. }
  41352. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41353. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41354. this.cone = new LineSegments( geometry, material );
  41355. this.add( this.cone );
  41356. this.update();
  41357. }
  41358. /**
  41359. * Frees the GPU-related resources allocated by this instance. Call this
  41360. * method whenever this instance is no longer used in your app.
  41361. */
  41362. dispose() {
  41363. this.cone.geometry.dispose();
  41364. this.cone.material.dispose();
  41365. }
  41366. /**
  41367. * Updates the helper to match the position and direction of the
  41368. * light being visualized.
  41369. */
  41370. update() {
  41371. this.light.updateWorldMatrix( true, false );
  41372. this.light.target.updateWorldMatrix( true, false );
  41373. // update the local matrix based on the parent and light target transforms
  41374. if ( this.parent ) {
  41375. this.parent.updateWorldMatrix( true );
  41376. this.matrix
  41377. .copy( this.parent.matrixWorld )
  41378. .invert()
  41379. .multiply( this.light.matrixWorld );
  41380. } else {
  41381. this.matrix.copy( this.light.matrixWorld );
  41382. }
  41383. this.matrixWorld.copy( this.light.matrixWorld );
  41384. const coneLength = this.light.distance ? this.light.distance : 1000;
  41385. const coneWidth = coneLength * Math.tan( this.light.angle );
  41386. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41387. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41388. this.cone.lookAt( _vector$3 );
  41389. if ( this.color !== undefined ) {
  41390. this.cone.material.color.set( this.color );
  41391. } else {
  41392. this.cone.material.color.copy( this.light.color );
  41393. }
  41394. }
  41395. }
  41396. const _vector$2 = /*@__PURE__*/ new Vector3();
  41397. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41398. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41399. /**
  41400. * A helper object to assist with visualizing a {@link Skeleton}.
  41401. *
  41402. * ```js
  41403. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41404. * scene.add( helper );
  41405. * ```
  41406. *
  41407. * @augments LineSegments
  41408. */
  41409. class SkeletonHelper extends LineSegments {
  41410. /**
  41411. * Constructs a new skeleton helper.
  41412. *
  41413. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41414. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41415. */
  41416. constructor( object ) {
  41417. const bones = getBoneList( object );
  41418. const geometry = new BufferGeometry();
  41419. const vertices = [];
  41420. const colors = [];
  41421. for ( let i = 0; i < bones.length; i ++ ) {
  41422. const bone = bones[ i ];
  41423. if ( bone.parent && bone.parent.isBone ) {
  41424. vertices.push( 0, 0, 0 );
  41425. vertices.push( 0, 0, 0 );
  41426. colors.push( 0, 0, 0 );
  41427. colors.push( 0, 0, 0 );
  41428. }
  41429. }
  41430. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41431. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41432. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41433. super( geometry, material );
  41434. /**
  41435. * This flag can be used for type testing.
  41436. *
  41437. * @type {boolean}
  41438. * @readonly
  41439. * @default true
  41440. */
  41441. this.isSkeletonHelper = true;
  41442. this.type = 'SkeletonHelper';
  41443. /**
  41444. * The object being visualized.
  41445. *
  41446. * @type {Object3D}
  41447. */
  41448. this.root = object;
  41449. /**
  41450. * The list of bones that the helper visualizes.
  41451. *
  41452. * @type {Array<Bone>}
  41453. */
  41454. this.bones = bones;
  41455. this.matrix = object.matrixWorld;
  41456. this.matrixAutoUpdate = false;
  41457. // colors
  41458. const color1 = new Color( 0x0000ff );
  41459. const color2 = new Color( 0x00ff00 );
  41460. this.setColors( color1, color2 );
  41461. }
  41462. updateMatrixWorld( force ) {
  41463. const bones = this.bones;
  41464. const geometry = this.geometry;
  41465. const position = geometry.getAttribute( 'position' );
  41466. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41467. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41468. const bone = bones[ i ];
  41469. if ( bone.parent && bone.parent.isBone ) {
  41470. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41471. _vector$2.setFromMatrixPosition( _boneMatrix );
  41472. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41473. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41474. _vector$2.setFromMatrixPosition( _boneMatrix );
  41475. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41476. j += 2;
  41477. }
  41478. }
  41479. geometry.getAttribute( 'position' ).needsUpdate = true;
  41480. super.updateMatrixWorld( force );
  41481. }
  41482. /**
  41483. * Defines the colors of the helper.
  41484. *
  41485. * @param {Color} color1 - The first line color for each bone.
  41486. * @param {Color} color2 - The second line color for each bone.
  41487. * @return {SkeletonHelper} A reference to this helper.
  41488. */
  41489. setColors( color1, color2 ) {
  41490. const geometry = this.geometry;
  41491. const colorAttribute = geometry.getAttribute( 'color' );
  41492. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41493. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41494. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41495. }
  41496. colorAttribute.needsUpdate = true;
  41497. return this;
  41498. }
  41499. /**
  41500. * Frees the GPU-related resources allocated by this instance. Call this
  41501. * method whenever this instance is no longer used in your app.
  41502. */
  41503. dispose() {
  41504. this.geometry.dispose();
  41505. this.material.dispose();
  41506. }
  41507. }
  41508. function getBoneList( object ) {
  41509. const boneList = [];
  41510. if ( object.isBone === true ) {
  41511. boneList.push( object );
  41512. }
  41513. for ( let i = 0; i < object.children.length; i ++ ) {
  41514. boneList.push( ...getBoneList( object.children[ i ] ) );
  41515. }
  41516. return boneList;
  41517. }
  41518. /**
  41519. * This displays a helper object consisting of a spherical mesh for
  41520. * visualizing an instance of {@link PointLight}.
  41521. *
  41522. * ```js
  41523. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41524. * pointLight.position.set( 10, 10, 10 );
  41525. * scene.add( pointLight );
  41526. *
  41527. * const sphereSize = 1;
  41528. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41529. * scene.add( pointLightHelper );
  41530. * ```
  41531. *
  41532. * @augments Mesh
  41533. */
  41534. class PointLightHelper extends Mesh {
  41535. /**
  41536. * Constructs a new point light helper.
  41537. *
  41538. * @param {PointLight} light - The light to be visualized.
  41539. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41540. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41541. * the color of the light.
  41542. */
  41543. constructor( light, sphereSize, color ) {
  41544. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41545. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41546. super( geometry, material );
  41547. /**
  41548. * The light being visualized.
  41549. *
  41550. * @type {PointLight}
  41551. */
  41552. this.light = light;
  41553. /**
  41554. * The color parameter passed in the constructor.
  41555. * If not set, the helper will take the color of the light.
  41556. *
  41557. * @type {number|Color|string}
  41558. */
  41559. this.color = color;
  41560. this.type = 'PointLightHelper';
  41561. this.matrix = this.light.matrixWorld;
  41562. this.matrixAutoUpdate = false;
  41563. this.update();
  41564. /*
  41565. // TODO: delete this comment?
  41566. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41567. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41568. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41569. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41570. const d = light.distance;
  41571. if ( d === 0.0 ) {
  41572. this.lightDistance.visible = false;
  41573. } else {
  41574. this.lightDistance.scale.set( d, d, d );
  41575. }
  41576. this.add( this.lightDistance );
  41577. */
  41578. }
  41579. /**
  41580. * Frees the GPU-related resources allocated by this instance. Call this
  41581. * method whenever this instance is no longer used in your app.
  41582. */
  41583. dispose() {
  41584. this.geometry.dispose();
  41585. this.material.dispose();
  41586. }
  41587. /**
  41588. * Updates the helper to match the position of the
  41589. * light being visualized.
  41590. */
  41591. update() {
  41592. this.light.updateWorldMatrix( true, false );
  41593. if ( this.color !== undefined ) {
  41594. this.material.color.set( this.color );
  41595. } else {
  41596. this.material.color.copy( this.light.color );
  41597. }
  41598. /*
  41599. const d = this.light.distance;
  41600. if ( d === 0.0 ) {
  41601. this.lightDistance.visible = false;
  41602. } else {
  41603. this.lightDistance.visible = true;
  41604. this.lightDistance.scale.set( d, d, d );
  41605. }
  41606. */
  41607. }
  41608. }
  41609. const _vector$1 = /*@__PURE__*/ new Vector3();
  41610. const _color1 = /*@__PURE__*/ new Color();
  41611. const _color2 = /*@__PURE__*/ new Color();
  41612. /**
  41613. * Creates a visual aid consisting of a spherical mesh for a
  41614. * given {@link HemisphereLight}.
  41615. *
  41616. * When the hemisphere light is transformed or its light properties are changed,
  41617. * it's necessary to call the `update()` method of the respective helper.
  41618. *
  41619. * ```js
  41620. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41621. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41622. * scene.add( helper );
  41623. * ```
  41624. *
  41625. * @augments Object3D
  41626. */
  41627. class HemisphereLightHelper extends Object3D {
  41628. /**
  41629. * Constructs a new hemisphere light helper.
  41630. *
  41631. * @param {HemisphereLight} light - The light to be visualized.
  41632. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41633. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41634. * the color of the light.
  41635. */
  41636. constructor( light, size, color ) {
  41637. super();
  41638. /**
  41639. * The light being visualized.
  41640. *
  41641. * @type {HemisphereLight}
  41642. */
  41643. this.light = light;
  41644. this.matrix = light.matrixWorld;
  41645. this.matrixAutoUpdate = false;
  41646. /**
  41647. * The color parameter passed in the constructor.
  41648. * If not set, the helper will take the color of the light.
  41649. *
  41650. * @type {number|Color|string}
  41651. */
  41652. this.color = color;
  41653. this.type = 'HemisphereLightHelper';
  41654. const geometry = new OctahedronGeometry( size );
  41655. geometry.rotateY( Math.PI * 0.5 );
  41656. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41657. if ( this.color === undefined ) this.material.vertexColors = true;
  41658. const position = geometry.getAttribute( 'position' );
  41659. const colors = new Float32Array( position.count * 3 );
  41660. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41661. this.add( new Mesh( geometry, this.material ) );
  41662. this.update();
  41663. }
  41664. /**
  41665. * Frees the GPU-related resources allocated by this instance. Call this
  41666. * method whenever this instance is no longer used in your app.
  41667. */
  41668. dispose() {
  41669. this.children[ 0 ].geometry.dispose();
  41670. this.children[ 0 ].material.dispose();
  41671. }
  41672. /**
  41673. * Updates the helper to match the position and direction of the
  41674. * light being visualized.
  41675. */
  41676. update() {
  41677. const mesh = this.children[ 0 ];
  41678. if ( this.color !== undefined ) {
  41679. this.material.color.set( this.color );
  41680. } else {
  41681. const colors = mesh.geometry.getAttribute( 'color' );
  41682. _color1.copy( this.light.color );
  41683. _color2.copy( this.light.groundColor );
  41684. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41685. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41686. colors.setXYZ( i, color.r, color.g, color.b );
  41687. }
  41688. colors.needsUpdate = true;
  41689. }
  41690. this.light.updateWorldMatrix( true, false );
  41691. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41692. }
  41693. }
  41694. /**
  41695. * The helper is an object to define grids. Grids are two-dimensional
  41696. * arrays of lines.
  41697. *
  41698. * ```js
  41699. * const size = 10;
  41700. * const divisions = 10;
  41701. *
  41702. * const gridHelper = new THREE.GridHelper( size, divisions );
  41703. * scene.add( gridHelper );
  41704. * ```
  41705. *
  41706. * @augments LineSegments
  41707. */
  41708. class GridHelper extends LineSegments {
  41709. /**
  41710. * Constructs a new grid helper.
  41711. *
  41712. * @param {number} [size=10] - The size of the grid.
  41713. * @param {number} [divisions=10] - The number of divisions across the grid.
  41714. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41715. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41716. */
  41717. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41718. color1 = new Color( color1 );
  41719. color2 = new Color( color2 );
  41720. const center = divisions / 2;
  41721. const step = size / divisions;
  41722. const halfSize = size / 2;
  41723. const vertices = [], colors = [];
  41724. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41725. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41726. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41727. const color = i === center ? color1 : color2;
  41728. color.toArray( colors, j ); j += 3;
  41729. color.toArray( colors, j ); j += 3;
  41730. color.toArray( colors, j ); j += 3;
  41731. color.toArray( colors, j ); j += 3;
  41732. }
  41733. const geometry = new BufferGeometry();
  41734. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41735. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41736. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41737. super( geometry, material );
  41738. this.type = 'GridHelper';
  41739. }
  41740. /**
  41741. * Frees the GPU-related resources allocated by this instance. Call this
  41742. * method whenever this instance is no longer used in your app.
  41743. */
  41744. dispose() {
  41745. this.geometry.dispose();
  41746. this.material.dispose();
  41747. }
  41748. }
  41749. /**
  41750. * This helper is an object to define polar grids. Grids are
  41751. * two-dimensional arrays of lines.
  41752. *
  41753. * ```js
  41754. * const radius = 10;
  41755. * const sectors = 16;
  41756. * const rings = 8;
  41757. * const divisions = 64;
  41758. *
  41759. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41760. * scene.add( helper );
  41761. * ```
  41762. *
  41763. * @augments LineSegments
  41764. */
  41765. class PolarGridHelper extends LineSegments {
  41766. /**
  41767. * Constructs a new polar grid helper.
  41768. *
  41769. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41770. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41771. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41772. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41773. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41774. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41775. */
  41776. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41777. color1 = new Color( color1 );
  41778. color2 = new Color( color2 );
  41779. const vertices = [];
  41780. const colors = [];
  41781. // create the sectors
  41782. if ( sectors > 1 ) {
  41783. for ( let i = 0; i < sectors; i ++ ) {
  41784. const v = ( i / sectors ) * ( Math.PI * 2 );
  41785. const x = Math.sin( v ) * radius;
  41786. const z = Math.cos( v ) * radius;
  41787. vertices.push( 0, 0, 0 );
  41788. vertices.push( x, 0, z );
  41789. const color = ( i & 1 ) ? color1 : color2;
  41790. colors.push( color.r, color.g, color.b );
  41791. colors.push( color.r, color.g, color.b );
  41792. }
  41793. }
  41794. // create the rings
  41795. for ( let i = 0; i < rings; i ++ ) {
  41796. const color = ( i & 1 ) ? color1 : color2;
  41797. const r = radius - ( radius / rings * i );
  41798. for ( let j = 0; j < divisions; j ++ ) {
  41799. // first vertex
  41800. let v = ( j / divisions ) * ( Math.PI * 2 );
  41801. let x = Math.sin( v ) * r;
  41802. let z = Math.cos( v ) * r;
  41803. vertices.push( x, 0, z );
  41804. colors.push( color.r, color.g, color.b );
  41805. // second vertex
  41806. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41807. x = Math.sin( v ) * r;
  41808. z = Math.cos( v ) * r;
  41809. vertices.push( x, 0, z );
  41810. colors.push( color.r, color.g, color.b );
  41811. }
  41812. }
  41813. const geometry = new BufferGeometry();
  41814. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41815. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41816. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41817. super( geometry, material );
  41818. this.type = 'PolarGridHelper';
  41819. }
  41820. /**
  41821. * Frees the GPU-related resources allocated by this instance. Call this
  41822. * method whenever this instance is no longer used in your app.
  41823. */
  41824. dispose() {
  41825. this.geometry.dispose();
  41826. this.material.dispose();
  41827. }
  41828. }
  41829. const _v1 = /*@__PURE__*/ new Vector3();
  41830. const _v2 = /*@__PURE__*/ new Vector3();
  41831. const _v3 = /*@__PURE__*/ new Vector3();
  41832. /**
  41833. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41834. * effect on the scene. This consists of a plane and a line representing the
  41835. * light's position and direction.
  41836. *
  41837. * When the directional light or its target are transformed or light properties
  41838. * are changed, it's necessary to call the `update()` method of the respective helper.
  41839. *
  41840. * ```js
  41841. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41842. * scene.add( light );
  41843. *
  41844. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41845. * scene.add( helper );
  41846. * ```
  41847. *
  41848. * @augments Object3D
  41849. */
  41850. class DirectionalLightHelper extends Object3D {
  41851. /**
  41852. * Constructs a new directional light helper.
  41853. *
  41854. * @param {DirectionalLight} light - The light to be visualized.
  41855. * @param {number} [size=1] - The dimensions of the plane.
  41856. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41857. * the color of the light.
  41858. */
  41859. constructor( light, size, color ) {
  41860. super();
  41861. /**
  41862. * The light being visualized.
  41863. *
  41864. * @type {DirectionalLight}
  41865. */
  41866. this.light = light;
  41867. this.matrix = light.matrixWorld;
  41868. this.matrixAutoUpdate = false;
  41869. /**
  41870. * The color parameter passed in the constructor.
  41871. * If not set, the helper will take the color of the light.
  41872. *
  41873. * @type {number|Color|string}
  41874. */
  41875. this.color = color;
  41876. this.type = 'DirectionalLightHelper';
  41877. if ( size === undefined ) size = 1;
  41878. let geometry = new BufferGeometry();
  41879. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41880. - size, size, 0,
  41881. size, size, 0,
  41882. size, - size, 0,
  41883. - size, - size, 0,
  41884. - size, size, 0
  41885. ], 3 ) );
  41886. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41887. /**
  41888. * Contains the line showing the location of the directional light.
  41889. *
  41890. * @type {Line}
  41891. */
  41892. this.lightPlane = new Line( geometry, material );
  41893. this.add( this.lightPlane );
  41894. geometry = new BufferGeometry();
  41895. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41896. /**
  41897. * Represents the target line of the directional light.
  41898. *
  41899. * @type {Line}
  41900. */
  41901. this.targetLine = new Line( geometry, material );
  41902. this.add( this.targetLine );
  41903. this.update();
  41904. }
  41905. /**
  41906. * Frees the GPU-related resources allocated by this instance. Call this
  41907. * method whenever this instance is no longer used in your app.
  41908. */
  41909. dispose() {
  41910. this.lightPlane.geometry.dispose();
  41911. this.lightPlane.material.dispose();
  41912. this.targetLine.geometry.dispose();
  41913. this.targetLine.material.dispose();
  41914. }
  41915. /**
  41916. * Updates the helper to match the position and direction of the
  41917. * light being visualized.
  41918. */
  41919. update() {
  41920. this.light.updateWorldMatrix( true, false );
  41921. this.light.target.updateWorldMatrix( true, false );
  41922. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41923. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41924. _v3.subVectors( _v2, _v1 );
  41925. this.lightPlane.lookAt( _v2 );
  41926. if ( this.color !== undefined ) {
  41927. this.lightPlane.material.color.set( this.color );
  41928. this.targetLine.material.color.set( this.color );
  41929. } else {
  41930. this.lightPlane.material.color.copy( this.light.color );
  41931. this.targetLine.material.color.copy( this.light.color );
  41932. }
  41933. this.targetLine.lookAt( _v2 );
  41934. this.targetLine.scale.z = _v3.length();
  41935. }
  41936. }
  41937. const _vector = /*@__PURE__*/ new Vector3();
  41938. const _camera = /*@__PURE__*/ new Camera();
  41939. /**
  41940. * This helps with visualizing what a camera contains in its frustum. It
  41941. * visualizes the frustum of a camera using a line segments.
  41942. *
  41943. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41944. *
  41945. * `CameraHelper` must be a child of the scene.
  41946. *
  41947. * When the camera is transformed or its projection matrix is changed, it's necessary
  41948. * to call the `update()` method of the respective helper.
  41949. *
  41950. * ```js
  41951. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41952. * const helper = new THREE.CameraHelper( camera );
  41953. * scene.add( helper );
  41954. * ```
  41955. *
  41956. * @augments LineSegments
  41957. */
  41958. class CameraHelper extends LineSegments {
  41959. /**
  41960. * Constructs a new arrow helper.
  41961. *
  41962. * @param {Camera} camera - The camera to visualize.
  41963. */
  41964. constructor( camera ) {
  41965. const geometry = new BufferGeometry();
  41966. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41967. const vertices = [];
  41968. const colors = [];
  41969. const pointMap = {};
  41970. // near
  41971. addLine( 'n1', 'n2' );
  41972. addLine( 'n2', 'n4' );
  41973. addLine( 'n4', 'n3' );
  41974. addLine( 'n3', 'n1' );
  41975. // far
  41976. addLine( 'f1', 'f2' );
  41977. addLine( 'f2', 'f4' );
  41978. addLine( 'f4', 'f3' );
  41979. addLine( 'f3', 'f1' );
  41980. // sides
  41981. addLine( 'n1', 'f1' );
  41982. addLine( 'n2', 'f2' );
  41983. addLine( 'n3', 'f3' );
  41984. addLine( 'n4', 'f4' );
  41985. // cone
  41986. addLine( 'p', 'n1' );
  41987. addLine( 'p', 'n2' );
  41988. addLine( 'p', 'n3' );
  41989. addLine( 'p', 'n4' );
  41990. // up
  41991. addLine( 'u1', 'u2' );
  41992. addLine( 'u2', 'u3' );
  41993. addLine( 'u3', 'u1' );
  41994. // target
  41995. addLine( 'c', 't' );
  41996. addLine( 'p', 'c' );
  41997. // cross
  41998. addLine( 'cn1', 'cn2' );
  41999. addLine( 'cn3', 'cn4' );
  42000. addLine( 'cf1', 'cf2' );
  42001. addLine( 'cf3', 'cf4' );
  42002. function addLine( a, b ) {
  42003. addPoint( a );
  42004. addPoint( b );
  42005. }
  42006. function addPoint( id ) {
  42007. vertices.push( 0, 0, 0 );
  42008. colors.push( 0, 0, 0 );
  42009. if ( pointMap[ id ] === undefined ) {
  42010. pointMap[ id ] = [];
  42011. }
  42012. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42013. }
  42014. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42015. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42016. super( geometry, material );
  42017. this.type = 'CameraHelper';
  42018. /**
  42019. * The camera being visualized.
  42020. *
  42021. * @type {Camera}
  42022. */
  42023. this.camera = camera;
  42024. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42025. this.matrix = camera.matrixWorld;
  42026. this.matrixAutoUpdate = false;
  42027. /**
  42028. * This contains the points used to visualize the camera.
  42029. *
  42030. * @type {Object<string,Array<number>>}
  42031. */
  42032. this.pointMap = pointMap;
  42033. this.update();
  42034. // colors
  42035. const colorFrustum = new Color( 0xffaa00 );
  42036. const colorCone = new Color( 0xff0000 );
  42037. const colorUp = new Color( 0x00aaff );
  42038. const colorTarget = new Color( 0xffffff );
  42039. const colorCross = new Color( 0x333333 );
  42040. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42041. }
  42042. /**
  42043. * Defines the colors of the helper.
  42044. *
  42045. * @param {Color} frustum - The frustum line color.
  42046. * @param {Color} cone - The cone line color.
  42047. * @param {Color} up - The up line color.
  42048. * @param {Color} target - The target line color.
  42049. * @param {Color} cross - The cross line color.
  42050. * @return {CameraHelper} A reference to this helper.
  42051. */
  42052. setColors( frustum, cone, up, target, cross ) {
  42053. const geometry = this.geometry;
  42054. const colorAttribute = geometry.getAttribute( 'color' );
  42055. // near
  42056. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42057. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42058. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42059. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42060. // far
  42061. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42062. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42063. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42064. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42065. // sides
  42066. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42067. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42068. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42069. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42070. // cone
  42071. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42072. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42073. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42074. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42075. // up
  42076. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42077. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42078. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42079. // target
  42080. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42081. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42082. // cross
  42083. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42084. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42085. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42086. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42087. colorAttribute.needsUpdate = true;
  42088. return this;
  42089. }
  42090. /**
  42091. * Updates the helper based on the projection matrix of the camera.
  42092. */
  42093. update() {
  42094. const geometry = this.geometry;
  42095. const pointMap = this.pointMap;
  42096. const w = 1, h = 1;
  42097. let nearZ, farZ;
  42098. // we need just camera projection matrix inverse
  42099. // world matrix must be identity
  42100. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42101. // Adjust z values based on coordinate system
  42102. if ( this.camera.reversedDepth === true ) {
  42103. nearZ = 1;
  42104. farZ = 0;
  42105. } else {
  42106. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42107. nearZ = -1;
  42108. farZ = 1;
  42109. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42110. nearZ = 0;
  42111. farZ = 1;
  42112. } else {
  42113. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42114. }
  42115. }
  42116. // center / target
  42117. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42118. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42119. // near
  42120. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42121. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42122. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42123. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42124. // far
  42125. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42126. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42127. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42128. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42129. // up
  42130. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42131. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42132. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42133. // cross
  42134. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42135. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42136. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42137. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42138. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42139. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42140. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42141. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42142. geometry.getAttribute( 'position' ).needsUpdate = true;
  42143. }
  42144. /**
  42145. * Frees the GPU-related resources allocated by this instance. Call this
  42146. * method whenever this instance is no longer used in your app.
  42147. */
  42148. dispose() {
  42149. this.geometry.dispose();
  42150. this.material.dispose();
  42151. }
  42152. }
  42153. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42154. _vector.set( x, y, z ).unproject( camera );
  42155. const points = pointMap[ point ];
  42156. if ( points !== undefined ) {
  42157. const position = geometry.getAttribute( 'position' );
  42158. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42159. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42160. }
  42161. }
  42162. }
  42163. const _box = /*@__PURE__*/ new Box3();
  42164. /**
  42165. * Helper object to graphically show the world-axis-aligned bounding box
  42166. * around an object. The actual bounding box is handled with {@link Box3},
  42167. * this is just a visual helper for debugging. It can be automatically
  42168. * resized with {@link BoxHelper#update} when the object it's created from
  42169. * is transformed. Note that the object must have a geometry for this to work,
  42170. * so it won't work with sprites.
  42171. *
  42172. * ```js
  42173. * const sphere = new THREE.SphereGeometry();
  42174. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42175. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42176. * scene.add( box );
  42177. * ```
  42178. *
  42179. * @augments LineSegments
  42180. */
  42181. class BoxHelper extends LineSegments {
  42182. /**
  42183. * Constructs a new box helper.
  42184. *
  42185. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42186. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42187. */
  42188. constructor( object, color = 0xffff00 ) {
  42189. 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 ] );
  42190. const positions = new Float32Array( 8 * 3 );
  42191. const geometry = new BufferGeometry();
  42192. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42193. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42194. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42195. /**
  42196. * The 3D object being visualized.
  42197. *
  42198. * @type {Object3D}
  42199. */
  42200. this.object = object;
  42201. this.type = 'BoxHelper';
  42202. this.matrixAutoUpdate = false;
  42203. this.update();
  42204. }
  42205. /**
  42206. * Updates the helper's geometry to match the dimensions of the object,
  42207. * including any children.
  42208. */
  42209. update() {
  42210. if ( this.object !== undefined ) {
  42211. _box.setFromObject( this.object );
  42212. }
  42213. if ( _box.isEmpty() ) return;
  42214. const min = _box.min;
  42215. const max = _box.max;
  42216. /*
  42217. 5____4
  42218. 1/___0/|
  42219. | 6__|_7
  42220. 2/___3/
  42221. 0: max.x, max.y, max.z
  42222. 1: min.x, max.y, max.z
  42223. 2: min.x, min.y, max.z
  42224. 3: max.x, min.y, max.z
  42225. 4: max.x, max.y, min.z
  42226. 5: min.x, max.y, min.z
  42227. 6: min.x, min.y, min.z
  42228. 7: max.x, min.y, min.z
  42229. */
  42230. const position = this.geometry.attributes.position;
  42231. const array = position.array;
  42232. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42233. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42234. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42235. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42236. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42237. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42238. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42239. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42240. position.needsUpdate = true;
  42241. this.geometry.computeBoundingSphere();
  42242. }
  42243. /**
  42244. * Updates the wireframe box for the passed object.
  42245. *
  42246. * @param {Object3D} object - The 3D object to create the helper for.
  42247. * @return {BoxHelper} A reference to this instance.
  42248. */
  42249. setFromObject( object ) {
  42250. this.object = object;
  42251. this.update();
  42252. return this;
  42253. }
  42254. copy( source, recursive ) {
  42255. super.copy( source, recursive );
  42256. this.object = source.object;
  42257. return this;
  42258. }
  42259. /**
  42260. * Frees the GPU-related resources allocated by this instance. Call this
  42261. * method whenever this instance is no longer used in your app.
  42262. */
  42263. dispose() {
  42264. this.geometry.dispose();
  42265. this.material.dispose();
  42266. }
  42267. }
  42268. /**
  42269. * A helper object to visualize an instance of {@link Box3}.
  42270. *
  42271. * ```js
  42272. * const box = new THREE.Box3();
  42273. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42274. *
  42275. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42276. * scene.add( helper )
  42277. * ```
  42278. *
  42279. * @augments LineSegments
  42280. */
  42281. class Box3Helper extends LineSegments {
  42282. /**
  42283. * Constructs a new box3 helper.
  42284. *
  42285. * @param {Box3} box - The box to visualize.
  42286. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42287. */
  42288. constructor( box, color = 0xffff00 ) {
  42289. 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 ] );
  42290. 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 ];
  42291. const geometry = new BufferGeometry();
  42292. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42293. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42294. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42295. /**
  42296. * The box being visualized.
  42297. *
  42298. * @type {Box3}
  42299. */
  42300. this.box = box;
  42301. this.type = 'Box3Helper';
  42302. this.geometry.computeBoundingSphere();
  42303. }
  42304. updateMatrixWorld( force ) {
  42305. const box = this.box;
  42306. if ( box.isEmpty() ) return;
  42307. box.getCenter( this.position );
  42308. box.getSize( this.scale );
  42309. this.scale.multiplyScalar( 0.5 );
  42310. super.updateMatrixWorld( force );
  42311. }
  42312. /**
  42313. * Frees the GPU-related resources allocated by this instance. Call this
  42314. * method whenever this instance is no longer used in your app.
  42315. */
  42316. dispose() {
  42317. this.geometry.dispose();
  42318. this.material.dispose();
  42319. }
  42320. }
  42321. /**
  42322. * A helper object to visualize an instance of {@link Plane}.
  42323. *
  42324. * ```js
  42325. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42326. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42327. * scene.add( helper );
  42328. * ```
  42329. *
  42330. * @augments Line
  42331. */
  42332. class PlaneHelper extends Line {
  42333. /**
  42334. * Constructs a new plane helper.
  42335. *
  42336. * @param {Plane} plane - The plane to be visualized.
  42337. * @param {number} [size=1] - The side length of plane helper.
  42338. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42339. */
  42340. constructor( plane, size = 1, hex = 0xffff00 ) {
  42341. const color = hex;
  42342. 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 ];
  42343. const geometry = new BufferGeometry();
  42344. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42345. geometry.computeBoundingSphere();
  42346. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42347. this.type = 'PlaneHelper';
  42348. /**
  42349. * The plane being visualized.
  42350. *
  42351. * @type {Plane}
  42352. */
  42353. this.plane = plane;
  42354. /**
  42355. * The side length of plane helper.
  42356. *
  42357. * @type {number}
  42358. * @default 1
  42359. */
  42360. this.size = size;
  42361. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42362. const geometry2 = new BufferGeometry();
  42363. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42364. geometry2.computeBoundingSphere();
  42365. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42366. }
  42367. updateMatrixWorld( force ) {
  42368. this.position.set( 0, 0, 0 );
  42369. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42370. this.lookAt( this.plane.normal );
  42371. this.translateZ( - this.plane.constant );
  42372. super.updateMatrixWorld( force );
  42373. }
  42374. /**
  42375. * Updates the helper to match the position and direction of the
  42376. * light being visualized.
  42377. */
  42378. dispose() {
  42379. this.geometry.dispose();
  42380. this.material.dispose();
  42381. this.children[ 0 ].geometry.dispose();
  42382. this.children[ 0 ].material.dispose();
  42383. }
  42384. }
  42385. const _axis = /*@__PURE__*/ new Vector3();
  42386. let _lineGeometry, _coneGeometry;
  42387. /**
  42388. * An 3D arrow object for visualizing directions.
  42389. *
  42390. * ```js
  42391. * const dir = new THREE.Vector3( 1, 2, 0 );
  42392. *
  42393. * //normalize the direction vector (convert to vector of length 1)
  42394. * dir.normalize();
  42395. *
  42396. * const origin = new THREE.Vector3( 0, 0, 0 );
  42397. * const length = 1;
  42398. * const hex = 0xffff00;
  42399. *
  42400. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42401. * scene.add( arrowHelper );
  42402. * ```
  42403. *
  42404. * @augments Object3D
  42405. */
  42406. class ArrowHelper extends Object3D {
  42407. /**
  42408. * Constructs a new arrow helper.
  42409. *
  42410. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42411. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42412. * @param {number} [length=1] - Length of the arrow in world units.
  42413. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42414. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42415. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42416. */
  42417. 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 ) {
  42418. super();
  42419. this.type = 'ArrowHelper';
  42420. if ( _lineGeometry === undefined ) {
  42421. _lineGeometry = new BufferGeometry();
  42422. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42423. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42424. _coneGeometry.translate( 0, -0.5, 0 );
  42425. }
  42426. this.position.copy( origin );
  42427. /**
  42428. * The line part of the arrow helper.
  42429. *
  42430. * @type {Line}
  42431. */
  42432. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42433. this.line.matrixAutoUpdate = false;
  42434. this.add( this.line );
  42435. /**
  42436. * The cone part of the arrow helper.
  42437. *
  42438. * @type {Mesh}
  42439. */
  42440. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42441. this.cone.matrixAutoUpdate = false;
  42442. this.add( this.cone );
  42443. this.setDirection( dir );
  42444. this.setLength( length, headLength, headWidth );
  42445. }
  42446. /**
  42447. * Sets the direction of the helper.
  42448. *
  42449. * @param {Vector3} dir - The normalized direction vector.
  42450. */
  42451. setDirection( dir ) {
  42452. // dir is assumed to be normalized
  42453. if ( dir.y > 0.99999 ) {
  42454. this.quaternion.set( 0, 0, 0, 1 );
  42455. } else if ( dir.y < -0.99999 ) {
  42456. this.quaternion.set( 1, 0, 0, 0 );
  42457. } else {
  42458. _axis.set( dir.z, 0, - dir.x ).normalize();
  42459. const radians = Math.acos( dir.y );
  42460. this.quaternion.setFromAxisAngle( _axis, radians );
  42461. }
  42462. }
  42463. /**
  42464. * Sets the length of the helper.
  42465. *
  42466. * @param {number} length - Length of the arrow in world units.
  42467. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42468. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42469. */
  42470. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42471. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42472. this.line.updateMatrix();
  42473. this.cone.scale.set( headWidth, headLength, headWidth );
  42474. this.cone.position.y = length;
  42475. this.cone.updateMatrix();
  42476. }
  42477. /**
  42478. * Sets the color of the helper.
  42479. *
  42480. * @param {number|Color|string} color - The color to set.
  42481. */
  42482. setColor( color ) {
  42483. this.line.material.color.set( color );
  42484. this.cone.material.color.set( color );
  42485. }
  42486. copy( source ) {
  42487. super.copy( source, false );
  42488. this.line.copy( source.line );
  42489. this.cone.copy( source.cone );
  42490. return this;
  42491. }
  42492. /**
  42493. * Frees the GPU-related resources allocated by this instance. Call this
  42494. * method whenever this instance is no longer used in your app.
  42495. */
  42496. dispose() {
  42497. this.line.geometry.dispose();
  42498. this.line.material.dispose();
  42499. this.cone.geometry.dispose();
  42500. this.cone.material.dispose();
  42501. }
  42502. }
  42503. /**
  42504. * An axis object to visualize the 3 axes in a simple way.
  42505. * The X axis is red. The Y axis is green. The Z axis is blue.
  42506. *
  42507. * ```js
  42508. * const axesHelper = new THREE.AxesHelper( 5 );
  42509. * scene.add( axesHelper );
  42510. * ```
  42511. *
  42512. * @augments LineSegments
  42513. */
  42514. class AxesHelper extends LineSegments {
  42515. /**
  42516. * Constructs a new axes helper.
  42517. *
  42518. * @param {number} [size=1] - Size of the lines representing the axes.
  42519. */
  42520. constructor( size = 1 ) {
  42521. const vertices = [
  42522. 0, 0, 0, size, 0, 0,
  42523. 0, 0, 0, 0, size, 0,
  42524. 0, 0, 0, 0, 0, size
  42525. ];
  42526. const colors = [
  42527. 1, 0, 0, 1, 0.6, 0,
  42528. 0, 1, 0, 0.6, 1, 0,
  42529. 0, 0, 1, 0, 0.6, 1
  42530. ];
  42531. const geometry = new BufferGeometry();
  42532. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42533. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42534. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42535. super( geometry, material );
  42536. this.type = 'AxesHelper';
  42537. }
  42538. /**
  42539. * Defines the colors of the axes helper.
  42540. *
  42541. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42542. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42543. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42544. * @return {AxesHelper} A reference to this axes helper.
  42545. */
  42546. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42547. const color = new Color();
  42548. const array = this.geometry.attributes.color.array;
  42549. color.set( xAxisColor );
  42550. color.toArray( array, 0 );
  42551. color.toArray( array, 3 );
  42552. color.set( yAxisColor );
  42553. color.toArray( array, 6 );
  42554. color.toArray( array, 9 );
  42555. color.set( zAxisColor );
  42556. color.toArray( array, 12 );
  42557. color.toArray( array, 15 );
  42558. this.geometry.attributes.color.needsUpdate = true;
  42559. return this;
  42560. }
  42561. /**
  42562. * Frees the GPU-related resources allocated by this instance. Call this
  42563. * method whenever this instance is no longer used in your app.
  42564. */
  42565. dispose() {
  42566. this.geometry.dispose();
  42567. this.material.dispose();
  42568. }
  42569. }
  42570. /**
  42571. * This class is used to convert a series of paths to an array of
  42572. * shapes. It is specifically used in context of fonts and SVG.
  42573. */
  42574. class ShapePath {
  42575. /**
  42576. * Constructs a new shape path.
  42577. */
  42578. constructor() {
  42579. this.type = 'ShapePath';
  42580. /**
  42581. * The color of the shape.
  42582. *
  42583. * @type {Color}
  42584. */
  42585. this.color = new Color();
  42586. /**
  42587. * The paths that have been generated for this shape.
  42588. *
  42589. * @type {Array<Path>}
  42590. * @default null
  42591. */
  42592. this.subPaths = [];
  42593. /**
  42594. * The current path that is being generated.
  42595. *
  42596. * @type {?Path}
  42597. * @default null
  42598. */
  42599. this.currentPath = null;
  42600. }
  42601. /**
  42602. * Creates a new path and moves it current point to the given one.
  42603. *
  42604. * @param {number} x - The x coordinate.
  42605. * @param {number} y - The y coordinate.
  42606. * @return {ShapePath} A reference to this shape path.
  42607. */
  42608. moveTo( x, y ) {
  42609. this.currentPath = new Path();
  42610. this.subPaths.push( this.currentPath );
  42611. this.currentPath.moveTo( x, y );
  42612. return this;
  42613. }
  42614. /**
  42615. * Adds an instance of {@link LineCurve} to the path by connecting
  42616. * the current point with the given one.
  42617. *
  42618. * @param {number} x - The x coordinate of the end point.
  42619. * @param {number} y - The y coordinate of the end point.
  42620. * @return {ShapePath} A reference to this shape path.
  42621. */
  42622. lineTo( x, y ) {
  42623. this.currentPath.lineTo( x, y );
  42624. return this;
  42625. }
  42626. /**
  42627. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42628. * the current point with the given one.
  42629. *
  42630. * @param {number} aCPx - The x coordinate of the control point.
  42631. * @param {number} aCPy - The y coordinate of the control point.
  42632. * @param {number} aX - The x coordinate of the end point.
  42633. * @param {number} aY - The y coordinate of the end point.
  42634. * @return {ShapePath} A reference to this shape path.
  42635. */
  42636. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42637. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42638. return this;
  42639. }
  42640. /**
  42641. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42642. * the current point with the given one.
  42643. *
  42644. * @param {number} aCP1x - The x coordinate of the first control point.
  42645. * @param {number} aCP1y - The y coordinate of the first control point.
  42646. * @param {number} aCP2x - The x coordinate of the second control point.
  42647. * @param {number} aCP2y - The y coordinate of the second control point.
  42648. * @param {number} aX - The x coordinate of the end point.
  42649. * @param {number} aY - The y coordinate of the end point.
  42650. * @return {ShapePath} A reference to this shape path.
  42651. */
  42652. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42653. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42654. return this;
  42655. }
  42656. /**
  42657. * Adds an instance of {@link SplineCurve} to the path by connecting
  42658. * the current point with the given list of points.
  42659. *
  42660. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42661. * @return {ShapePath} A reference to this shape path.
  42662. */
  42663. splineThru( pts ) {
  42664. this.currentPath.splineThru( pts );
  42665. return this;
  42666. }
  42667. /**
  42668. * Converts the paths into an array of shapes.
  42669. *
  42670. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42671. * If this flag is set to `true`, then those are flipped.
  42672. * @return {Array<Shape>} An array of shapes.
  42673. */
  42674. toShapes( isCCW ) {
  42675. function toShapesNoHoles( inSubpaths ) {
  42676. const shapes = [];
  42677. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42678. const tmpPath = inSubpaths[ i ];
  42679. const tmpShape = new Shape();
  42680. tmpShape.curves = tmpPath.curves;
  42681. shapes.push( tmpShape );
  42682. }
  42683. return shapes;
  42684. }
  42685. function isPointInsidePolygon( inPt, inPolygon ) {
  42686. const polyLen = inPolygon.length;
  42687. // inPt on polygon contour => immediate success or
  42688. // toggling of inside/outside at every single! intersection point of an edge
  42689. // with the horizontal line through inPt, left of inPt
  42690. // not counting lowerY endpoints of edges and whole edges on that line
  42691. let inside = false;
  42692. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42693. let edgeLowPt = inPolygon[ p ];
  42694. let edgeHighPt = inPolygon[ q ];
  42695. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42696. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42697. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42698. // not parallel
  42699. if ( edgeDy < 0 ) {
  42700. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42701. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42702. }
  42703. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42704. if ( inPt.y === edgeLowPt.y ) {
  42705. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42706. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42707. } else {
  42708. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42709. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42710. if ( perpEdge < 0 ) continue;
  42711. inside = ! inside; // true intersection left of inPt
  42712. }
  42713. } else {
  42714. // parallel or collinear
  42715. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42716. // edge lies on the same horizontal line as inPt
  42717. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42718. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42719. // continue;
  42720. }
  42721. }
  42722. return inside;
  42723. }
  42724. const isClockWise = ShapeUtils.isClockWise;
  42725. const subPaths = this.subPaths;
  42726. if ( subPaths.length === 0 ) return [];
  42727. let solid, tmpPath, tmpShape;
  42728. const shapes = [];
  42729. if ( subPaths.length === 1 ) {
  42730. tmpPath = subPaths[ 0 ];
  42731. tmpShape = new Shape();
  42732. tmpShape.curves = tmpPath.curves;
  42733. shapes.push( tmpShape );
  42734. return shapes;
  42735. }
  42736. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42737. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42738. // log("Holes first", holesFirst);
  42739. const betterShapeHoles = [];
  42740. const newShapes = [];
  42741. let newShapeHoles = [];
  42742. let mainIdx = 0;
  42743. let tmpPoints;
  42744. newShapes[ mainIdx ] = undefined;
  42745. newShapeHoles[ mainIdx ] = [];
  42746. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42747. tmpPath = subPaths[ i ];
  42748. tmpPoints = tmpPath.getPoints();
  42749. solid = isClockWise( tmpPoints );
  42750. solid = isCCW ? ! solid : solid;
  42751. if ( solid ) {
  42752. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42753. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42754. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42755. if ( holesFirst ) mainIdx ++;
  42756. newShapeHoles[ mainIdx ] = [];
  42757. //log('cw', i);
  42758. } else {
  42759. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42760. //log('ccw', i);
  42761. }
  42762. }
  42763. // only Holes? -> probably all Shapes with wrong orientation
  42764. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42765. if ( newShapes.length > 1 ) {
  42766. let ambiguous = false;
  42767. let toChange = 0;
  42768. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42769. betterShapeHoles[ sIdx ] = [];
  42770. }
  42771. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42772. const sho = newShapeHoles[ sIdx ];
  42773. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42774. const ho = sho[ hIdx ];
  42775. let hole_unassigned = true;
  42776. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42777. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42778. if ( sIdx !== s2Idx ) toChange ++;
  42779. if ( hole_unassigned ) {
  42780. hole_unassigned = false;
  42781. betterShapeHoles[ s2Idx ].push( ho );
  42782. } else {
  42783. ambiguous = true;
  42784. }
  42785. }
  42786. }
  42787. if ( hole_unassigned ) {
  42788. betterShapeHoles[ sIdx ].push( ho );
  42789. }
  42790. }
  42791. }
  42792. if ( toChange > 0 && ambiguous === false ) {
  42793. newShapeHoles = betterShapeHoles;
  42794. }
  42795. }
  42796. let tmpHoles;
  42797. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42798. tmpShape = newShapes[ i ].s;
  42799. shapes.push( tmpShape );
  42800. tmpHoles = newShapeHoles[ i ];
  42801. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42802. tmpShape.holes.push( tmpHoles[ j ].h );
  42803. }
  42804. }
  42805. //log("shape", shapes);
  42806. return shapes;
  42807. }
  42808. }
  42809. /**
  42810. * Abstract base class for controls.
  42811. *
  42812. * @abstract
  42813. * @augments EventDispatcher
  42814. */
  42815. class Controls extends EventDispatcher {
  42816. /**
  42817. * Constructs a new controls instance.
  42818. *
  42819. * @param {Object3D} object - The object that is managed by the controls.
  42820. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42821. */
  42822. constructor( object, domElement = null ) {
  42823. super();
  42824. /**
  42825. * The object that is managed by the controls.
  42826. *
  42827. * @type {Object3D}
  42828. */
  42829. this.object = object;
  42830. /**
  42831. * The HTML element used for event listeners.
  42832. *
  42833. * @type {?HTMLElement}
  42834. * @default null
  42835. */
  42836. this.domElement = domElement;
  42837. /**
  42838. * Whether the controls responds to user input or not.
  42839. *
  42840. * @type {boolean}
  42841. * @default true
  42842. */
  42843. this.enabled = true;
  42844. /**
  42845. * The internal state of the controls.
  42846. *
  42847. * @type {number}
  42848. * @default -1
  42849. */
  42850. this.state = -1;
  42851. /**
  42852. * This object defines the keyboard input of the controls.
  42853. *
  42854. * @type {Object}
  42855. */
  42856. this.keys = {};
  42857. /**
  42858. * This object defines what type of actions are assigned to the available mouse buttons.
  42859. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42860. *
  42861. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42862. */
  42863. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42864. /**
  42865. * This object defines what type of actions are assigned to what kind of touch interaction.
  42866. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42867. *
  42868. * @type {{ONE: ?number, TWO: ?number}}
  42869. */
  42870. this.touches = { ONE: null, TWO: null };
  42871. }
  42872. /**
  42873. * Connects the controls to the DOM. This method has so called "side effects" since
  42874. * it adds the module's event listeners to the DOM.
  42875. *
  42876. * @param {HTMLElement} element - The DOM element to connect to.
  42877. */
  42878. connect( element ) {
  42879. if ( element === undefined ) {
  42880. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42881. return;
  42882. }
  42883. if ( this.domElement !== null ) this.disconnect();
  42884. this.domElement = element;
  42885. }
  42886. /**
  42887. * Disconnects the controls from the DOM.
  42888. */
  42889. disconnect() {}
  42890. /**
  42891. * Call this method if you no longer want use to the controls. It frees all internal
  42892. * resources and removes all event listeners.
  42893. */
  42894. dispose() {}
  42895. /**
  42896. * Controls should implement this method if they have to update their internal state
  42897. * per simulation step.
  42898. *
  42899. * @param {number} [delta] - The time delta in seconds.
  42900. */
  42901. update( /* delta */ ) {}
  42902. }
  42903. /**
  42904. * Scales the texture as large as possible within its surface without cropping
  42905. * or stretching the texture. The method preserves the original aspect ratio of
  42906. * the texture. Akin to CSS `object-fit: contain`
  42907. *
  42908. * @param {Texture} texture - The texture.
  42909. * @param {number} aspect - The texture's aspect ratio.
  42910. * @return {Texture} The updated texture.
  42911. */
  42912. function contain( texture, aspect ) {
  42913. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42914. if ( imageAspect > aspect ) {
  42915. texture.repeat.x = 1;
  42916. texture.repeat.y = imageAspect / aspect;
  42917. texture.offset.x = 0;
  42918. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42919. } else {
  42920. texture.repeat.x = aspect / imageAspect;
  42921. texture.repeat.y = 1;
  42922. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42923. texture.offset.y = 0;
  42924. }
  42925. return texture;
  42926. }
  42927. /**
  42928. * Scales the texture to the smallest possible size to fill the surface, leaving
  42929. * no empty space. The method preserves the original aspect ratio of the texture.
  42930. * Akin to CSS `object-fit: cover`.
  42931. *
  42932. * @param {Texture} texture - The texture.
  42933. * @param {number} aspect - The texture's aspect ratio.
  42934. * @return {Texture} The updated texture.
  42935. */
  42936. function cover( texture, aspect ) {
  42937. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42938. if ( imageAspect > aspect ) {
  42939. texture.repeat.x = aspect / imageAspect;
  42940. texture.repeat.y = 1;
  42941. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42942. texture.offset.y = 0;
  42943. } else {
  42944. texture.repeat.x = 1;
  42945. texture.repeat.y = imageAspect / aspect;
  42946. texture.offset.x = 0;
  42947. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42948. }
  42949. return texture;
  42950. }
  42951. /**
  42952. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42953. *
  42954. * @param {Texture} texture - The texture.
  42955. * @return {Texture} The updated texture.
  42956. */
  42957. function fill( texture ) {
  42958. texture.repeat.x = 1;
  42959. texture.repeat.y = 1;
  42960. texture.offset.x = 0;
  42961. texture.offset.y = 0;
  42962. return texture;
  42963. }
  42964. /**
  42965. * Determines how many bytes must be used to represent the texture.
  42966. *
  42967. * @param {number} width - The width of the texture.
  42968. * @param {number} height - The height of the texture.
  42969. * @param {number} format - The texture's format.
  42970. * @param {number} type - The texture's type.
  42971. * @return {number} The byte length.
  42972. */
  42973. function getByteLength( width, height, format, type ) {
  42974. const typeByteLength = getTextureTypeByteLength( type );
  42975. switch ( format ) {
  42976. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42977. case AlphaFormat:
  42978. return width * height;
  42979. case RedFormat:
  42980. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42981. case RedIntegerFormat:
  42982. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42983. case RGFormat:
  42984. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42985. case RGIntegerFormat:
  42986. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42987. case RGBFormat:
  42988. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42989. case RGBAFormat:
  42990. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42991. case RGBAIntegerFormat:
  42992. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42993. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42994. case RGB_S3TC_DXT1_Format:
  42995. case RGBA_S3TC_DXT1_Format:
  42996. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42997. case RGBA_S3TC_DXT3_Format:
  42998. case RGBA_S3TC_DXT5_Format:
  42999. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43000. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43001. case RGB_PVRTC_2BPPV1_Format:
  43002. case RGBA_PVRTC_2BPPV1_Format:
  43003. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43004. case RGB_PVRTC_4BPPV1_Format:
  43005. case RGBA_PVRTC_4BPPV1_Format:
  43006. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43007. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43008. case RGB_ETC1_Format:
  43009. case RGB_ETC2_Format:
  43010. case R11_EAC_Format:
  43011. case SIGNED_R11_EAC_Format:
  43012. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43013. case RGBA_ETC2_EAC_Format:
  43014. case RG11_EAC_Format:
  43015. case SIGNED_RG11_EAC_Format:
  43016. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43017. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43018. case RGBA_ASTC_4x4_Format:
  43019. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43020. case RGBA_ASTC_5x4_Format:
  43021. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43022. case RGBA_ASTC_5x5_Format:
  43023. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43024. case RGBA_ASTC_6x5_Format:
  43025. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43026. case RGBA_ASTC_6x6_Format:
  43027. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43028. case RGBA_ASTC_8x5_Format:
  43029. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43030. case RGBA_ASTC_8x6_Format:
  43031. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43032. case RGBA_ASTC_8x8_Format:
  43033. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43034. case RGBA_ASTC_10x5_Format:
  43035. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43036. case RGBA_ASTC_10x6_Format:
  43037. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43038. case RGBA_ASTC_10x8_Format:
  43039. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43040. case RGBA_ASTC_10x10_Format:
  43041. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43042. case RGBA_ASTC_12x10_Format:
  43043. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43044. case RGBA_ASTC_12x12_Format:
  43045. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43046. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43047. case RGBA_BPTC_Format:
  43048. case RGB_BPTC_SIGNED_Format:
  43049. case RGB_BPTC_UNSIGNED_Format:
  43050. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43051. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43052. case RED_RGTC1_Format:
  43053. case SIGNED_RED_RGTC1_Format:
  43054. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43055. case RED_GREEN_RGTC2_Format:
  43056. case SIGNED_RED_GREEN_RGTC2_Format:
  43057. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43058. }
  43059. throw new Error(
  43060. `Unable to determine texture byte length for ${format} format.`,
  43061. );
  43062. }
  43063. function getTextureTypeByteLength( type ) {
  43064. switch ( type ) {
  43065. case UnsignedByteType:
  43066. case ByteType:
  43067. return { byteLength: 1, components: 1 };
  43068. case UnsignedShortType:
  43069. case ShortType:
  43070. case HalfFloatType:
  43071. return { byteLength: 2, components: 1 };
  43072. case UnsignedShort4444Type:
  43073. case UnsignedShort5551Type:
  43074. return { byteLength: 2, components: 4 };
  43075. case UnsignedIntType:
  43076. case IntType:
  43077. case FloatType:
  43078. return { byteLength: 4, components: 1 };
  43079. case UnsignedInt5999Type:
  43080. case UnsignedInt101111Type:
  43081. return { byteLength: 4, components: 3 };
  43082. }
  43083. throw new Error( `Unknown texture type ${type}.` );
  43084. }
  43085. /**
  43086. * A class containing utility functions for textures.
  43087. *
  43088. * @hideconstructor
  43089. */
  43090. class TextureUtils {
  43091. /**
  43092. * Scales the texture as large as possible within its surface without cropping
  43093. * or stretching the texture. The method preserves the original aspect ratio of
  43094. * the texture. Akin to CSS `object-fit: contain`
  43095. *
  43096. * @param {Texture} texture - The texture.
  43097. * @param {number} aspect - The texture's aspect ratio.
  43098. * @return {Texture} The updated texture.
  43099. */
  43100. static contain( texture, aspect ) {
  43101. return contain( texture, aspect );
  43102. }
  43103. /**
  43104. * Scales the texture to the smallest possible size to fill the surface, leaving
  43105. * no empty space. The method preserves the original aspect ratio of the texture.
  43106. * Akin to CSS `object-fit: cover`.
  43107. *
  43108. * @param {Texture} texture - The texture.
  43109. * @param {number} aspect - The texture's aspect ratio.
  43110. * @return {Texture} The updated texture.
  43111. */
  43112. static cover( texture, aspect ) {
  43113. return cover( texture, aspect );
  43114. }
  43115. /**
  43116. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43117. *
  43118. * @param {Texture} texture - The texture.
  43119. * @return {Texture} The updated texture.
  43120. */
  43121. static fill( texture ) {
  43122. return fill( texture );
  43123. }
  43124. /**
  43125. * Determines how many bytes must be used to represent the texture.
  43126. *
  43127. * @param {number} width - The width of the texture.
  43128. * @param {number} height - The height of the texture.
  43129. * @param {number} format - The texture's format.
  43130. * @param {number} type - The texture's type.
  43131. * @return {number} The byte length.
  43132. */
  43133. static getByteLength( width, height, format, type ) {
  43134. return getByteLength( width, height, format, type );
  43135. }
  43136. }
  43137. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43138. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43139. revision: REVISION,
  43140. } } ) );
  43141. }
  43142. if ( typeof window !== 'undefined' ) {
  43143. if ( window.__THREE__ ) {
  43144. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43145. } else {
  43146. window.__THREE__ = REVISION;
  43147. }
  43148. }
  43149. function WebGLAnimation() {
  43150. let context = null;
  43151. let isAnimating = false;
  43152. let animationLoop = null;
  43153. let requestId = null;
  43154. function onAnimationFrame( time, frame ) {
  43155. animationLoop( time, frame );
  43156. requestId = context.requestAnimationFrame( onAnimationFrame );
  43157. }
  43158. return {
  43159. start: function () {
  43160. if ( isAnimating === true ) return;
  43161. if ( animationLoop === null ) return;
  43162. requestId = context.requestAnimationFrame( onAnimationFrame );
  43163. isAnimating = true;
  43164. },
  43165. stop: function () {
  43166. context.cancelAnimationFrame( requestId );
  43167. isAnimating = false;
  43168. },
  43169. setAnimationLoop: function ( callback ) {
  43170. animationLoop = callback;
  43171. },
  43172. setContext: function ( value ) {
  43173. context = value;
  43174. }
  43175. };
  43176. }
  43177. function WebGLAttributes( gl ) {
  43178. const buffers = new WeakMap();
  43179. function createBuffer( attribute, bufferType ) {
  43180. const array = attribute.array;
  43181. const usage = attribute.usage;
  43182. const size = array.byteLength;
  43183. const buffer = gl.createBuffer();
  43184. gl.bindBuffer( bufferType, buffer );
  43185. gl.bufferData( bufferType, array, usage );
  43186. attribute.onUploadCallback();
  43187. let type;
  43188. if ( array instanceof Float32Array ) {
  43189. type = gl.FLOAT;
  43190. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  43191. type = gl.HALF_FLOAT;
  43192. } else if ( array instanceof Uint16Array ) {
  43193. if ( attribute.isFloat16BufferAttribute ) {
  43194. type = gl.HALF_FLOAT;
  43195. } else {
  43196. type = gl.UNSIGNED_SHORT;
  43197. }
  43198. } else if ( array instanceof Int16Array ) {
  43199. type = gl.SHORT;
  43200. } else if ( array instanceof Uint32Array ) {
  43201. type = gl.UNSIGNED_INT;
  43202. } else if ( array instanceof Int32Array ) {
  43203. type = gl.INT;
  43204. } else if ( array instanceof Int8Array ) {
  43205. type = gl.BYTE;
  43206. } else if ( array instanceof Uint8Array ) {
  43207. type = gl.UNSIGNED_BYTE;
  43208. } else if ( array instanceof Uint8ClampedArray ) {
  43209. type = gl.UNSIGNED_BYTE;
  43210. } else {
  43211. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  43212. }
  43213. return {
  43214. buffer: buffer,
  43215. type: type,
  43216. bytesPerElement: array.BYTES_PER_ELEMENT,
  43217. version: attribute.version,
  43218. size: size
  43219. };
  43220. }
  43221. function updateBuffer( buffer, attribute, bufferType ) {
  43222. const array = attribute.array;
  43223. const updateRanges = attribute.updateRanges;
  43224. gl.bindBuffer( bufferType, buffer );
  43225. if ( updateRanges.length === 0 ) {
  43226. // Not using update ranges
  43227. gl.bufferSubData( bufferType, 0, array );
  43228. } else {
  43229. // Before applying update ranges, we merge any adjacent / overlapping
  43230. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  43231. // to performance improvements for applications which make heavy use of
  43232. // update ranges. Likely due to GPU command overhead.
  43233. //
  43234. // Note that to reduce garbage collection between frames, we merge the
  43235. // update ranges in-place. This is safe because this method will clear the
  43236. // update ranges once updated.
  43237. updateRanges.sort( ( a, b ) => a.start - b.start );
  43238. // To merge the update ranges in-place, we work from left to right in the
  43239. // existing updateRanges array, merging ranges. This may result in a final
  43240. // array which is smaller than the original. This index tracks the last
  43241. // index representing a merged range, any data after this index can be
  43242. // trimmed once the merge algorithm is completed.
  43243. let mergeIndex = 0;
  43244. for ( let i = 1; i < updateRanges.length; i ++ ) {
  43245. const previousRange = updateRanges[ mergeIndex ];
  43246. const range = updateRanges[ i ];
  43247. // We add one here to merge adjacent ranges. This is safe because ranges
  43248. // operate over positive integers.
  43249. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  43250. previousRange.count = Math.max(
  43251. previousRange.count,
  43252. range.start + range.count - previousRange.start
  43253. );
  43254. } else {
  43255. ++ mergeIndex;
  43256. updateRanges[ mergeIndex ] = range;
  43257. }
  43258. }
  43259. // Trim the array to only contain the merged ranges.
  43260. updateRanges.length = mergeIndex + 1;
  43261. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43262. const range = updateRanges[ i ];
  43263. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  43264. array, range.start, range.count );
  43265. }
  43266. attribute.clearUpdateRanges();
  43267. }
  43268. attribute.onUploadCallback();
  43269. }
  43270. //
  43271. function get( attribute ) {
  43272. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43273. return buffers.get( attribute );
  43274. }
  43275. function remove( attribute ) {
  43276. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43277. const data = buffers.get( attribute );
  43278. if ( data ) {
  43279. gl.deleteBuffer( data.buffer );
  43280. buffers.delete( attribute );
  43281. }
  43282. }
  43283. function update( attribute, bufferType ) {
  43284. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43285. if ( attribute.isGLBufferAttribute ) {
  43286. const cached = buffers.get( attribute );
  43287. if ( ! cached || cached.version < attribute.version ) {
  43288. buffers.set( attribute, {
  43289. buffer: attribute.buffer,
  43290. type: attribute.type,
  43291. bytesPerElement: attribute.elementSize,
  43292. version: attribute.version
  43293. } );
  43294. }
  43295. return;
  43296. }
  43297. const data = buffers.get( attribute );
  43298. if ( data === undefined ) {
  43299. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  43300. } else if ( data.version < attribute.version ) {
  43301. if ( data.size !== attribute.array.byteLength ) {
  43302. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  43303. }
  43304. updateBuffer( data.buffer, attribute, bufferType );
  43305. data.version = attribute.version;
  43306. }
  43307. }
  43308. return {
  43309. get: get,
  43310. remove: remove,
  43311. update: update
  43312. };
  43313. }
  43314. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  43315. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  43316. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  43317. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  43318. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  43319. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  43320. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  43321. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  43322. var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec4 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 );\n\t}\n#endif";
  43323. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  43324. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  43325. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  43326. var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated";
  43327. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  43328. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  43329. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  43330. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  43331. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  43332. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  43333. var color_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif";
  43334. var color_pars_fragment = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif";
  43335. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif";
  43336. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif";
  43337. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  43338. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  43339. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  43340. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  43341. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  43342. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  43343. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  43344. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  43345. var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  43346. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\n\t#endif\n#endif";
  43347. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif";
  43348. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  43349. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  43350. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  43351. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  43352. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  43353. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  43354. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  43355. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  43356. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  43357. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  43358. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  43359. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  43360. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  43361. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  43362. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  43363. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  43364. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  43365. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  43366. var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  43367. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  43368. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  43369. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  43370. var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  43371. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43372. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43373. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  43374. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  43375. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  43376. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  43377. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  43378. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  43379. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  43380. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  43381. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  43382. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  43383. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif";
  43384. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  43385. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  43386. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  43387. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  43388. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  43389. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  43390. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  43391. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  43392. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  43393. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  43394. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43395. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  43396. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\n}";
  43397. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43398. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  43399. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43400. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  43401. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43402. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43403. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  43404. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  43405. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  43406. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  43407. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  43408. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  43409. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  43410. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  43411. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  43412. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43413. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43414. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  43415. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  43416. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  43417. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  43418. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  43419. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  43420. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  43421. const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  43422. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43423. const vertex$g = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  43424. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43425. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  43426. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43427. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  43428. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  43429. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  43430. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}";
  43431. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  43432. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43433. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  43434. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43435. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  43436. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43437. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43438. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43439. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  43440. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43441. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  43442. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  43443. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43444. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43445. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  43446. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43447. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43448. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43449. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  43450. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43451. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43452. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43453. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  43454. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  43455. const ShaderChunk = {
  43456. alphahash_fragment: alphahash_fragment,
  43457. alphahash_pars_fragment: alphahash_pars_fragment,
  43458. alphamap_fragment: alphamap_fragment,
  43459. alphamap_pars_fragment: alphamap_pars_fragment,
  43460. alphatest_fragment: alphatest_fragment,
  43461. alphatest_pars_fragment: alphatest_pars_fragment,
  43462. aomap_fragment: aomap_fragment,
  43463. aomap_pars_fragment: aomap_pars_fragment,
  43464. batching_pars_vertex: batching_pars_vertex,
  43465. batching_vertex: batching_vertex,
  43466. begin_vertex: begin_vertex,
  43467. beginnormal_vertex: beginnormal_vertex,
  43468. bsdfs: bsdfs,
  43469. iridescence_fragment: iridescence_fragment,
  43470. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43471. clipping_planes_fragment: clipping_planes_fragment,
  43472. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43473. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43474. clipping_planes_vertex: clipping_planes_vertex,
  43475. color_fragment: color_fragment,
  43476. color_pars_fragment: color_pars_fragment,
  43477. color_pars_vertex: color_pars_vertex,
  43478. color_vertex: color_vertex,
  43479. common: common,
  43480. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43481. defaultnormal_vertex: defaultnormal_vertex,
  43482. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43483. displacementmap_vertex: displacementmap_vertex,
  43484. emissivemap_fragment: emissivemap_fragment,
  43485. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43486. colorspace_fragment: colorspace_fragment,
  43487. colorspace_pars_fragment: colorspace_pars_fragment,
  43488. envmap_fragment: envmap_fragment,
  43489. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43490. envmap_pars_fragment: envmap_pars_fragment,
  43491. envmap_pars_vertex: envmap_pars_vertex,
  43492. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43493. envmap_vertex: envmap_vertex,
  43494. fog_vertex: fog_vertex,
  43495. fog_pars_vertex: fog_pars_vertex,
  43496. fog_fragment: fog_fragment,
  43497. fog_pars_fragment: fog_pars_fragment,
  43498. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43499. lightmap_pars_fragment: lightmap_pars_fragment,
  43500. lights_lambert_fragment: lights_lambert_fragment,
  43501. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43502. lights_pars_begin: lights_pars_begin,
  43503. lights_toon_fragment: lights_toon_fragment,
  43504. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43505. lights_phong_fragment: lights_phong_fragment,
  43506. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43507. lights_physical_fragment: lights_physical_fragment,
  43508. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43509. lights_fragment_begin: lights_fragment_begin,
  43510. lights_fragment_maps: lights_fragment_maps,
  43511. lights_fragment_end: lights_fragment_end,
  43512. logdepthbuf_fragment: logdepthbuf_fragment,
  43513. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43514. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43515. logdepthbuf_vertex: logdepthbuf_vertex,
  43516. map_fragment: map_fragment,
  43517. map_pars_fragment: map_pars_fragment,
  43518. map_particle_fragment: map_particle_fragment,
  43519. map_particle_pars_fragment: map_particle_pars_fragment,
  43520. metalnessmap_fragment: metalnessmap_fragment,
  43521. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43522. morphinstance_vertex: morphinstance_vertex,
  43523. morphcolor_vertex: morphcolor_vertex,
  43524. morphnormal_vertex: morphnormal_vertex,
  43525. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43526. morphtarget_vertex: morphtarget_vertex,
  43527. normal_fragment_begin: normal_fragment_begin,
  43528. normal_fragment_maps: normal_fragment_maps,
  43529. normal_pars_fragment: normal_pars_fragment,
  43530. normal_pars_vertex: normal_pars_vertex,
  43531. normal_vertex: normal_vertex,
  43532. normalmap_pars_fragment: normalmap_pars_fragment,
  43533. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43534. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43535. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43536. iridescence_pars_fragment: iridescence_pars_fragment,
  43537. opaque_fragment: opaque_fragment,
  43538. packing: packing,
  43539. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43540. project_vertex: project_vertex,
  43541. dithering_fragment: dithering_fragment,
  43542. dithering_pars_fragment: dithering_pars_fragment,
  43543. roughnessmap_fragment: roughnessmap_fragment,
  43544. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43545. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43546. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43547. shadowmap_vertex: shadowmap_vertex,
  43548. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43549. skinbase_vertex: skinbase_vertex,
  43550. skinning_pars_vertex: skinning_pars_vertex,
  43551. skinning_vertex: skinning_vertex,
  43552. skinnormal_vertex: skinnormal_vertex,
  43553. specularmap_fragment: specularmap_fragment,
  43554. specularmap_pars_fragment: specularmap_pars_fragment,
  43555. tonemapping_fragment: tonemapping_fragment,
  43556. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43557. transmission_fragment: transmission_fragment,
  43558. transmission_pars_fragment: transmission_pars_fragment,
  43559. uv_pars_fragment: uv_pars_fragment,
  43560. uv_pars_vertex: uv_pars_vertex,
  43561. uv_vertex: uv_vertex,
  43562. worldpos_vertex: worldpos_vertex,
  43563. background_vert: vertex$h,
  43564. background_frag: fragment$h,
  43565. backgroundCube_vert: vertex$g,
  43566. backgroundCube_frag: fragment$g,
  43567. cube_vert: vertex$f,
  43568. cube_frag: fragment$f,
  43569. depth_vert: vertex$e,
  43570. depth_frag: fragment$e,
  43571. distance_vert: vertex$d,
  43572. distance_frag: fragment$d,
  43573. equirect_vert: vertex$c,
  43574. equirect_frag: fragment$c,
  43575. linedashed_vert: vertex$b,
  43576. linedashed_frag: fragment$b,
  43577. meshbasic_vert: vertex$a,
  43578. meshbasic_frag: fragment$a,
  43579. meshlambert_vert: vertex$9,
  43580. meshlambert_frag: fragment$9,
  43581. meshmatcap_vert: vertex$8,
  43582. meshmatcap_frag: fragment$8,
  43583. meshnormal_vert: vertex$7,
  43584. meshnormal_frag: fragment$7,
  43585. meshphong_vert: vertex$6,
  43586. meshphong_frag: fragment$6,
  43587. meshphysical_vert: vertex$5,
  43588. meshphysical_frag: fragment$5,
  43589. meshtoon_vert: vertex$4,
  43590. meshtoon_frag: fragment$4,
  43591. points_vert: vertex$3,
  43592. points_frag: fragment$3,
  43593. shadow_vert: vertex$2,
  43594. shadow_frag: fragment$2,
  43595. sprite_vert: vertex$1,
  43596. sprite_frag: fragment$1
  43597. };
  43598. // Uniforms library for shared webgl shaders
  43599. const UniformsLib = {
  43600. common: {
  43601. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43602. opacity: { value: 1.0 },
  43603. map: { value: null },
  43604. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43605. alphaMap: { value: null },
  43606. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43607. alphaTest: { value: 0 }
  43608. },
  43609. specularmap: {
  43610. specularMap: { value: null },
  43611. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43612. },
  43613. envmap: {
  43614. envMap: { value: null },
  43615. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43616. flipEnvMap: { value: -1 },
  43617. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43618. ior: { value: 1.5 }, // physical
  43619. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43620. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43621. },
  43622. aomap: {
  43623. aoMap: { value: null },
  43624. aoMapIntensity: { value: 1 },
  43625. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43626. },
  43627. lightmap: {
  43628. lightMap: { value: null },
  43629. lightMapIntensity: { value: 1 },
  43630. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43631. },
  43632. bumpmap: {
  43633. bumpMap: { value: null },
  43634. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43635. bumpScale: { value: 1 }
  43636. },
  43637. normalmap: {
  43638. normalMap: { value: null },
  43639. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43640. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43641. },
  43642. displacementmap: {
  43643. displacementMap: { value: null },
  43644. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43645. displacementScale: { value: 1 },
  43646. displacementBias: { value: 0 }
  43647. },
  43648. emissivemap: {
  43649. emissiveMap: { value: null },
  43650. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43651. },
  43652. metalnessmap: {
  43653. metalnessMap: { value: null },
  43654. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43655. },
  43656. roughnessmap: {
  43657. roughnessMap: { value: null },
  43658. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43659. },
  43660. gradientmap: {
  43661. gradientMap: { value: null }
  43662. },
  43663. fog: {
  43664. fogDensity: { value: 0.00025 },
  43665. fogNear: { value: 1 },
  43666. fogFar: { value: 2000 },
  43667. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43668. },
  43669. lights: {
  43670. ambientLightColor: { value: [] },
  43671. lightProbe: { value: [] },
  43672. directionalLights: { value: [], properties: {
  43673. direction: {},
  43674. color: {}
  43675. } },
  43676. directionalLightShadows: { value: [], properties: {
  43677. shadowIntensity: 1,
  43678. shadowBias: {},
  43679. shadowNormalBias: {},
  43680. shadowRadius: {},
  43681. shadowMapSize: {}
  43682. } },
  43683. directionalShadowMatrix: { value: [] },
  43684. spotLights: { value: [], properties: {
  43685. color: {},
  43686. position: {},
  43687. direction: {},
  43688. distance: {},
  43689. coneCos: {},
  43690. penumbraCos: {},
  43691. decay: {}
  43692. } },
  43693. spotLightShadows: { value: [], properties: {
  43694. shadowIntensity: 1,
  43695. shadowBias: {},
  43696. shadowNormalBias: {},
  43697. shadowRadius: {},
  43698. shadowMapSize: {}
  43699. } },
  43700. spotLightMap: { value: [] },
  43701. spotLightMatrix: { value: [] },
  43702. pointLights: { value: [], properties: {
  43703. color: {},
  43704. position: {},
  43705. decay: {},
  43706. distance: {}
  43707. } },
  43708. pointLightShadows: { value: [], properties: {
  43709. shadowIntensity: 1,
  43710. shadowBias: {},
  43711. shadowNormalBias: {},
  43712. shadowRadius: {},
  43713. shadowMapSize: {},
  43714. shadowCameraNear: {},
  43715. shadowCameraFar: {}
  43716. } },
  43717. pointShadowMatrix: { value: [] },
  43718. hemisphereLights: { value: [], properties: {
  43719. direction: {},
  43720. skyColor: {},
  43721. groundColor: {}
  43722. } },
  43723. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43724. rectAreaLights: { value: [], properties: {
  43725. color: {},
  43726. position: {},
  43727. width: {},
  43728. height: {}
  43729. } },
  43730. ltc_1: { value: null },
  43731. ltc_2: { value: null }
  43732. },
  43733. points: {
  43734. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43735. opacity: { value: 1.0 },
  43736. size: { value: 1.0 },
  43737. scale: { value: 1.0 },
  43738. map: { value: null },
  43739. alphaMap: { value: null },
  43740. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43741. alphaTest: { value: 0 },
  43742. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43743. },
  43744. sprite: {
  43745. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43746. opacity: { value: 1.0 },
  43747. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43748. rotation: { value: 0.0 },
  43749. map: { value: null },
  43750. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43751. alphaMap: { value: null },
  43752. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43753. alphaTest: { value: 0 }
  43754. }
  43755. };
  43756. const ShaderLib = {
  43757. basic: {
  43758. uniforms: /*@__PURE__*/ mergeUniforms( [
  43759. UniformsLib.common,
  43760. UniformsLib.specularmap,
  43761. UniformsLib.envmap,
  43762. UniformsLib.aomap,
  43763. UniformsLib.lightmap,
  43764. UniformsLib.fog
  43765. ] ),
  43766. vertexShader: ShaderChunk.meshbasic_vert,
  43767. fragmentShader: ShaderChunk.meshbasic_frag
  43768. },
  43769. lambert: {
  43770. uniforms: /*@__PURE__*/ mergeUniforms( [
  43771. UniformsLib.common,
  43772. UniformsLib.specularmap,
  43773. UniformsLib.envmap,
  43774. UniformsLib.aomap,
  43775. UniformsLib.lightmap,
  43776. UniformsLib.emissivemap,
  43777. UniformsLib.bumpmap,
  43778. UniformsLib.normalmap,
  43779. UniformsLib.displacementmap,
  43780. UniformsLib.fog,
  43781. UniformsLib.lights,
  43782. {
  43783. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43784. envMapIntensity: { value: 1 }
  43785. }
  43786. ] ),
  43787. vertexShader: ShaderChunk.meshlambert_vert,
  43788. fragmentShader: ShaderChunk.meshlambert_frag
  43789. },
  43790. phong: {
  43791. uniforms: /*@__PURE__*/ mergeUniforms( [
  43792. UniformsLib.common,
  43793. UniformsLib.specularmap,
  43794. UniformsLib.envmap,
  43795. UniformsLib.aomap,
  43796. UniformsLib.lightmap,
  43797. UniformsLib.emissivemap,
  43798. UniformsLib.bumpmap,
  43799. UniformsLib.normalmap,
  43800. UniformsLib.displacementmap,
  43801. UniformsLib.fog,
  43802. UniformsLib.lights,
  43803. {
  43804. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43805. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43806. shininess: { value: 30 },
  43807. envMapIntensity: { value: 1 }
  43808. }
  43809. ] ),
  43810. vertexShader: ShaderChunk.meshphong_vert,
  43811. fragmentShader: ShaderChunk.meshphong_frag
  43812. },
  43813. standard: {
  43814. uniforms: /*@__PURE__*/ mergeUniforms( [
  43815. UniformsLib.common,
  43816. UniformsLib.envmap,
  43817. UniformsLib.aomap,
  43818. UniformsLib.lightmap,
  43819. UniformsLib.emissivemap,
  43820. UniformsLib.bumpmap,
  43821. UniformsLib.normalmap,
  43822. UniformsLib.displacementmap,
  43823. UniformsLib.roughnessmap,
  43824. UniformsLib.metalnessmap,
  43825. UniformsLib.fog,
  43826. UniformsLib.lights,
  43827. {
  43828. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43829. roughness: { value: 1.0 },
  43830. metalness: { value: 0.0 },
  43831. envMapIntensity: { value: 1 }
  43832. }
  43833. ] ),
  43834. vertexShader: ShaderChunk.meshphysical_vert,
  43835. fragmentShader: ShaderChunk.meshphysical_frag
  43836. },
  43837. toon: {
  43838. uniforms: /*@__PURE__*/ mergeUniforms( [
  43839. UniformsLib.common,
  43840. UniformsLib.aomap,
  43841. UniformsLib.lightmap,
  43842. UniformsLib.emissivemap,
  43843. UniformsLib.bumpmap,
  43844. UniformsLib.normalmap,
  43845. UniformsLib.displacementmap,
  43846. UniformsLib.gradientmap,
  43847. UniformsLib.fog,
  43848. UniformsLib.lights,
  43849. {
  43850. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43851. }
  43852. ] ),
  43853. vertexShader: ShaderChunk.meshtoon_vert,
  43854. fragmentShader: ShaderChunk.meshtoon_frag
  43855. },
  43856. matcap: {
  43857. uniforms: /*@__PURE__*/ mergeUniforms( [
  43858. UniformsLib.common,
  43859. UniformsLib.bumpmap,
  43860. UniformsLib.normalmap,
  43861. UniformsLib.displacementmap,
  43862. UniformsLib.fog,
  43863. {
  43864. matcap: { value: null }
  43865. }
  43866. ] ),
  43867. vertexShader: ShaderChunk.meshmatcap_vert,
  43868. fragmentShader: ShaderChunk.meshmatcap_frag
  43869. },
  43870. points: {
  43871. uniforms: /*@__PURE__*/ mergeUniforms( [
  43872. UniformsLib.points,
  43873. UniformsLib.fog
  43874. ] ),
  43875. vertexShader: ShaderChunk.points_vert,
  43876. fragmentShader: ShaderChunk.points_frag
  43877. },
  43878. dashed: {
  43879. uniforms: /*@__PURE__*/ mergeUniforms( [
  43880. UniformsLib.common,
  43881. UniformsLib.fog,
  43882. {
  43883. scale: { value: 1 },
  43884. dashSize: { value: 1 },
  43885. totalSize: { value: 2 }
  43886. }
  43887. ] ),
  43888. vertexShader: ShaderChunk.linedashed_vert,
  43889. fragmentShader: ShaderChunk.linedashed_frag
  43890. },
  43891. depth: {
  43892. uniforms: /*@__PURE__*/ mergeUniforms( [
  43893. UniformsLib.common,
  43894. UniformsLib.displacementmap
  43895. ] ),
  43896. vertexShader: ShaderChunk.depth_vert,
  43897. fragmentShader: ShaderChunk.depth_frag
  43898. },
  43899. normal: {
  43900. uniforms: /*@__PURE__*/ mergeUniforms( [
  43901. UniformsLib.common,
  43902. UniformsLib.bumpmap,
  43903. UniformsLib.normalmap,
  43904. UniformsLib.displacementmap,
  43905. {
  43906. opacity: { value: 1.0 }
  43907. }
  43908. ] ),
  43909. vertexShader: ShaderChunk.meshnormal_vert,
  43910. fragmentShader: ShaderChunk.meshnormal_frag
  43911. },
  43912. sprite: {
  43913. uniforms: /*@__PURE__*/ mergeUniforms( [
  43914. UniformsLib.sprite,
  43915. UniformsLib.fog
  43916. ] ),
  43917. vertexShader: ShaderChunk.sprite_vert,
  43918. fragmentShader: ShaderChunk.sprite_frag
  43919. },
  43920. background: {
  43921. uniforms: {
  43922. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43923. t2D: { value: null },
  43924. backgroundIntensity: { value: 1 }
  43925. },
  43926. vertexShader: ShaderChunk.background_vert,
  43927. fragmentShader: ShaderChunk.background_frag
  43928. },
  43929. backgroundCube: {
  43930. uniforms: {
  43931. envMap: { value: null },
  43932. flipEnvMap: { value: -1 },
  43933. backgroundBlurriness: { value: 0 },
  43934. backgroundIntensity: { value: 1 },
  43935. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43936. },
  43937. vertexShader: ShaderChunk.backgroundCube_vert,
  43938. fragmentShader: ShaderChunk.backgroundCube_frag
  43939. },
  43940. cube: {
  43941. uniforms: {
  43942. tCube: { value: null },
  43943. tFlip: { value: -1 },
  43944. opacity: { value: 1.0 }
  43945. },
  43946. vertexShader: ShaderChunk.cube_vert,
  43947. fragmentShader: ShaderChunk.cube_frag
  43948. },
  43949. equirect: {
  43950. uniforms: {
  43951. tEquirect: { value: null },
  43952. },
  43953. vertexShader: ShaderChunk.equirect_vert,
  43954. fragmentShader: ShaderChunk.equirect_frag
  43955. },
  43956. distance: {
  43957. uniforms: /*@__PURE__*/ mergeUniforms( [
  43958. UniformsLib.common,
  43959. UniformsLib.displacementmap,
  43960. {
  43961. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43962. nearDistance: { value: 1 },
  43963. farDistance: { value: 1000 }
  43964. }
  43965. ] ),
  43966. vertexShader: ShaderChunk.distance_vert,
  43967. fragmentShader: ShaderChunk.distance_frag
  43968. },
  43969. shadow: {
  43970. uniforms: /*@__PURE__*/ mergeUniforms( [
  43971. UniformsLib.lights,
  43972. UniformsLib.fog,
  43973. {
  43974. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43975. opacity: { value: 1.0 }
  43976. },
  43977. ] ),
  43978. vertexShader: ShaderChunk.shadow_vert,
  43979. fragmentShader: ShaderChunk.shadow_frag
  43980. }
  43981. };
  43982. ShaderLib.physical = {
  43983. uniforms: /*@__PURE__*/ mergeUniforms( [
  43984. ShaderLib.standard.uniforms,
  43985. {
  43986. clearcoat: { value: 0 },
  43987. clearcoatMap: { value: null },
  43988. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43989. clearcoatNormalMap: { value: null },
  43990. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43991. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43992. clearcoatRoughness: { value: 0 },
  43993. clearcoatRoughnessMap: { value: null },
  43994. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43995. dispersion: { value: 0 },
  43996. iridescence: { value: 0 },
  43997. iridescenceMap: { value: null },
  43998. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43999. iridescenceIOR: { value: 1.3 },
  44000. iridescenceThicknessMinimum: { value: 100 },
  44001. iridescenceThicknessMaximum: { value: 400 },
  44002. iridescenceThicknessMap: { value: null },
  44003. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44004. sheen: { value: 0 },
  44005. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  44006. sheenColorMap: { value: null },
  44007. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44008. sheenRoughness: { value: 1 },
  44009. sheenRoughnessMap: { value: null },
  44010. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44011. transmission: { value: 0 },
  44012. transmissionMap: { value: null },
  44013. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44014. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  44015. transmissionSamplerMap: { value: null },
  44016. thickness: { value: 0 },
  44017. thicknessMap: { value: null },
  44018. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44019. attenuationDistance: { value: 0 },
  44020. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  44021. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  44022. specularColorMap: { value: null },
  44023. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44024. specularIntensity: { value: 1 },
  44025. specularIntensityMap: { value: null },
  44026. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44027. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  44028. anisotropyMap: { value: null },
  44029. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  44030. }
  44031. ] ),
  44032. vertexShader: ShaderChunk.meshphysical_vert,
  44033. fragmentShader: ShaderChunk.meshphysical_frag
  44034. };
  44035. const _rgb = { r: 0, b: 0, g: 0 };
  44036. const _e1$1 = /*@__PURE__*/ new Euler();
  44037. const _m1$1 = /*@__PURE__*/ new Matrix4();
  44038. function WebGLBackground( renderer, environments, state, objects, alpha, premultipliedAlpha ) {
  44039. const clearColor = new Color( 0x000000 );
  44040. let clearAlpha = alpha === true ? 0 : 1;
  44041. let planeMesh;
  44042. let boxMesh;
  44043. let currentBackground = null;
  44044. let currentBackgroundVersion = 0;
  44045. let currentTonemapping = null;
  44046. function getBackground( scene ) {
  44047. let background = scene.isScene === true ? scene.background : null;
  44048. if ( background && background.isTexture ) {
  44049. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  44050. background = environments.get( background, usePMREM );
  44051. }
  44052. return background;
  44053. }
  44054. function render( scene ) {
  44055. let forceClear = false;
  44056. const background = getBackground( scene );
  44057. if ( background === null ) {
  44058. setClear( clearColor, clearAlpha );
  44059. } else if ( background && background.isColor ) {
  44060. setClear( background, 1 );
  44061. forceClear = true;
  44062. }
  44063. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  44064. if ( environmentBlendMode === 'additive' ) {
  44065. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  44066. } else if ( environmentBlendMode === 'alpha-blend' ) {
  44067. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  44068. }
  44069. if ( renderer.autoClear || forceClear ) {
  44070. // buffers might not be writable which is required to ensure a correct clear
  44071. state.buffers.depth.setTest( true );
  44072. state.buffers.depth.setMask( true );
  44073. state.buffers.color.setMask( true );
  44074. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  44075. }
  44076. }
  44077. function addToRenderList( renderList, scene ) {
  44078. const background = getBackground( scene );
  44079. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  44080. if ( boxMesh === undefined ) {
  44081. boxMesh = new Mesh(
  44082. new BoxGeometry( 1, 1, 1 ),
  44083. new ShaderMaterial( {
  44084. name: 'BackgroundCubeMaterial',
  44085. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  44086. vertexShader: ShaderLib.backgroundCube.vertexShader,
  44087. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  44088. side: BackSide,
  44089. depthTest: false,
  44090. depthWrite: false,
  44091. fog: false,
  44092. allowOverride: false
  44093. } )
  44094. );
  44095. boxMesh.geometry.deleteAttribute( 'normal' );
  44096. boxMesh.geometry.deleteAttribute( 'uv' );
  44097. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  44098. this.matrixWorld.copyPosition( camera.matrixWorld );
  44099. };
  44100. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  44101. Object.defineProperty( boxMesh.material, 'envMap', {
  44102. get: function () {
  44103. return this.uniforms.envMap.value;
  44104. }
  44105. } );
  44106. objects.update( boxMesh );
  44107. }
  44108. _e1$1.copy( scene.backgroundRotation );
  44109. // accommodate left-handed frame
  44110. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  44111. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  44112. // environment maps which are not cube render targets or PMREMs follow a different convention
  44113. _e1$1.y *= -1;
  44114. _e1$1.z *= -1;
  44115. }
  44116. boxMesh.material.uniforms.envMap.value = background;
  44117. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  44118. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  44119. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  44120. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  44121. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  44122. if ( currentBackground !== background ||
  44123. currentBackgroundVersion !== background.version ||
  44124. currentTonemapping !== renderer.toneMapping ) {
  44125. boxMesh.material.needsUpdate = true;
  44126. currentBackground = background;
  44127. currentBackgroundVersion = background.version;
  44128. currentTonemapping = renderer.toneMapping;
  44129. }
  44130. boxMesh.layers.enableAll();
  44131. // push to the pre-sorted opaque render list
  44132. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  44133. } else if ( background && background.isTexture ) {
  44134. if ( planeMesh === undefined ) {
  44135. planeMesh = new Mesh(
  44136. new PlaneGeometry( 2, 2 ),
  44137. new ShaderMaterial( {
  44138. name: 'BackgroundMaterial',
  44139. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  44140. vertexShader: ShaderLib.background.vertexShader,
  44141. fragmentShader: ShaderLib.background.fragmentShader,
  44142. side: FrontSide,
  44143. depthTest: false,
  44144. depthWrite: false,
  44145. fog: false,
  44146. allowOverride: false
  44147. } )
  44148. );
  44149. planeMesh.geometry.deleteAttribute( 'normal' );
  44150. // add "map" material property so the renderer can evaluate it like for built-in materials
  44151. Object.defineProperty( planeMesh.material, 'map', {
  44152. get: function () {
  44153. return this.uniforms.t2D.value;
  44154. }
  44155. } );
  44156. objects.update( planeMesh );
  44157. }
  44158. planeMesh.material.uniforms.t2D.value = background;
  44159. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  44160. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  44161. if ( background.matrixAutoUpdate === true ) {
  44162. background.updateMatrix();
  44163. }
  44164. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  44165. if ( currentBackground !== background ||
  44166. currentBackgroundVersion !== background.version ||
  44167. currentTonemapping !== renderer.toneMapping ) {
  44168. planeMesh.material.needsUpdate = true;
  44169. currentBackground = background;
  44170. currentBackgroundVersion = background.version;
  44171. currentTonemapping = renderer.toneMapping;
  44172. }
  44173. planeMesh.layers.enableAll();
  44174. // push to the pre-sorted opaque render list
  44175. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  44176. }
  44177. }
  44178. function setClear( color, alpha ) {
  44179. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  44180. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  44181. }
  44182. function dispose() {
  44183. if ( boxMesh !== undefined ) {
  44184. boxMesh.geometry.dispose();
  44185. boxMesh.material.dispose();
  44186. boxMesh = undefined;
  44187. }
  44188. if ( planeMesh !== undefined ) {
  44189. planeMesh.geometry.dispose();
  44190. planeMesh.material.dispose();
  44191. planeMesh = undefined;
  44192. }
  44193. }
  44194. return {
  44195. getClearColor: function () {
  44196. return clearColor;
  44197. },
  44198. setClearColor: function ( color, alpha = 1 ) {
  44199. clearColor.set( color );
  44200. clearAlpha = alpha;
  44201. setClear( clearColor, clearAlpha );
  44202. },
  44203. getClearAlpha: function () {
  44204. return clearAlpha;
  44205. },
  44206. setClearAlpha: function ( alpha ) {
  44207. clearAlpha = alpha;
  44208. setClear( clearColor, clearAlpha );
  44209. },
  44210. render: render,
  44211. addToRenderList: addToRenderList,
  44212. dispose: dispose
  44213. };
  44214. }
  44215. function WebGLBindingStates( gl, attributes ) {
  44216. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44217. const bindingStates = {};
  44218. const defaultState = createBindingState( null );
  44219. let currentState = defaultState;
  44220. let forceUpdate = false;
  44221. function setup( object, material, program, geometry, index ) {
  44222. let updateBuffers = false;
  44223. const state = getBindingState( object, geometry, program, material );
  44224. if ( currentState !== state ) {
  44225. currentState = state;
  44226. bindVertexArrayObject( currentState.object );
  44227. }
  44228. updateBuffers = needsUpdate( object, geometry, program, index );
  44229. if ( updateBuffers ) saveCache( object, geometry, program, index );
  44230. if ( index !== null ) {
  44231. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  44232. }
  44233. if ( updateBuffers || forceUpdate ) {
  44234. forceUpdate = false;
  44235. setupVertexAttributes( object, material, program, geometry );
  44236. if ( index !== null ) {
  44237. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  44238. }
  44239. }
  44240. }
  44241. function createVertexArrayObject() {
  44242. return gl.createVertexArray();
  44243. }
  44244. function bindVertexArrayObject( vao ) {
  44245. return gl.bindVertexArray( vao );
  44246. }
  44247. function deleteVertexArrayObject( vao ) {
  44248. return gl.deleteVertexArray( vao );
  44249. }
  44250. function getBindingState( object, geometry, program, material ) {
  44251. const wireframe = ( material.wireframe === true );
  44252. let objectMap = bindingStates[ geometry.id ];
  44253. if ( objectMap === undefined ) {
  44254. objectMap = {};
  44255. bindingStates[ geometry.id ] = objectMap;
  44256. }
  44257. // Each InstancedMesh requires unique binding states because it contains instanced attributes.
  44258. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44259. let programMap = objectMap[ objectId ];
  44260. if ( programMap === undefined ) {
  44261. programMap = {};
  44262. objectMap[ objectId ] = programMap;
  44263. }
  44264. let stateMap = programMap[ program.id ];
  44265. if ( stateMap === undefined ) {
  44266. stateMap = {};
  44267. programMap[ program.id ] = stateMap;
  44268. }
  44269. let state = stateMap[ wireframe ];
  44270. if ( state === undefined ) {
  44271. state = createBindingState( createVertexArrayObject() );
  44272. stateMap[ wireframe ] = state;
  44273. }
  44274. return state;
  44275. }
  44276. function createBindingState( vao ) {
  44277. const newAttributes = [];
  44278. const enabledAttributes = [];
  44279. const attributeDivisors = [];
  44280. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  44281. newAttributes[ i ] = 0;
  44282. enabledAttributes[ i ] = 0;
  44283. attributeDivisors[ i ] = 0;
  44284. }
  44285. return {
  44286. // for backward compatibility on non-VAO support browser
  44287. geometry: null,
  44288. program: null,
  44289. wireframe: false,
  44290. newAttributes: newAttributes,
  44291. enabledAttributes: enabledAttributes,
  44292. attributeDivisors: attributeDivisors,
  44293. object: vao,
  44294. attributes: {},
  44295. index: null
  44296. };
  44297. }
  44298. function needsUpdate( object, geometry, program, index ) {
  44299. const cachedAttributes = currentState.attributes;
  44300. const geometryAttributes = geometry.attributes;
  44301. let attributesNum = 0;
  44302. const programAttributes = program.getAttributes();
  44303. for ( const name in programAttributes ) {
  44304. const programAttribute = programAttributes[ name ];
  44305. if ( programAttribute.location >= 0 ) {
  44306. const cachedAttribute = cachedAttributes[ name ];
  44307. let geometryAttribute = geometryAttributes[ name ];
  44308. if ( geometryAttribute === undefined ) {
  44309. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44310. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44311. }
  44312. if ( cachedAttribute === undefined ) return true;
  44313. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  44314. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  44315. attributesNum ++;
  44316. }
  44317. }
  44318. if ( currentState.attributesNum !== attributesNum ) return true;
  44319. if ( currentState.index !== index ) return true;
  44320. return false;
  44321. }
  44322. function saveCache( object, geometry, program, index ) {
  44323. const cache = {};
  44324. const attributes = geometry.attributes;
  44325. let attributesNum = 0;
  44326. const programAttributes = program.getAttributes();
  44327. for ( const name in programAttributes ) {
  44328. const programAttribute = programAttributes[ name ];
  44329. if ( programAttribute.location >= 0 ) {
  44330. let attribute = attributes[ name ];
  44331. if ( attribute === undefined ) {
  44332. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  44333. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  44334. }
  44335. const data = {};
  44336. data.attribute = attribute;
  44337. if ( attribute && attribute.data ) {
  44338. data.data = attribute.data;
  44339. }
  44340. cache[ name ] = data;
  44341. attributesNum ++;
  44342. }
  44343. }
  44344. currentState.attributes = cache;
  44345. currentState.attributesNum = attributesNum;
  44346. currentState.index = index;
  44347. }
  44348. function initAttributes() {
  44349. const newAttributes = currentState.newAttributes;
  44350. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  44351. newAttributes[ i ] = 0;
  44352. }
  44353. }
  44354. function enableAttribute( attribute ) {
  44355. enableAttributeAndDivisor( attribute, 0 );
  44356. }
  44357. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  44358. const newAttributes = currentState.newAttributes;
  44359. const enabledAttributes = currentState.enabledAttributes;
  44360. const attributeDivisors = currentState.attributeDivisors;
  44361. newAttributes[ attribute ] = 1;
  44362. if ( enabledAttributes[ attribute ] === 0 ) {
  44363. gl.enableVertexAttribArray( attribute );
  44364. enabledAttributes[ attribute ] = 1;
  44365. }
  44366. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  44367. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  44368. attributeDivisors[ attribute ] = meshPerAttribute;
  44369. }
  44370. }
  44371. function disableUnusedAttributes() {
  44372. const newAttributes = currentState.newAttributes;
  44373. const enabledAttributes = currentState.enabledAttributes;
  44374. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  44375. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  44376. gl.disableVertexAttribArray( i );
  44377. enabledAttributes[ i ] = 0;
  44378. }
  44379. }
  44380. }
  44381. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  44382. if ( integer === true ) {
  44383. gl.vertexAttribIPointer( index, size, type, stride, offset );
  44384. } else {
  44385. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  44386. }
  44387. }
  44388. function setupVertexAttributes( object, material, program, geometry ) {
  44389. initAttributes();
  44390. const geometryAttributes = geometry.attributes;
  44391. const programAttributes = program.getAttributes();
  44392. const materialDefaultAttributeValues = material.defaultAttributeValues;
  44393. for ( const name in programAttributes ) {
  44394. const programAttribute = programAttributes[ name ];
  44395. if ( programAttribute.location >= 0 ) {
  44396. let geometryAttribute = geometryAttributes[ name ];
  44397. if ( geometryAttribute === undefined ) {
  44398. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44399. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44400. }
  44401. if ( geometryAttribute !== undefined ) {
  44402. const normalized = geometryAttribute.normalized;
  44403. const size = geometryAttribute.itemSize;
  44404. const attribute = attributes.get( geometryAttribute );
  44405. // TODO Attribute may not be available on context restore
  44406. if ( attribute === undefined ) continue;
  44407. const buffer = attribute.buffer;
  44408. const type = attribute.type;
  44409. const bytesPerElement = attribute.bytesPerElement;
  44410. // check for integer attributes
  44411. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44412. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44413. const data = geometryAttribute.data;
  44414. const stride = data.stride;
  44415. const offset = geometryAttribute.offset;
  44416. if ( data.isInstancedInterleavedBuffer ) {
  44417. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44418. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44419. }
  44420. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44421. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44422. }
  44423. } else {
  44424. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44425. enableAttribute( programAttribute.location + i );
  44426. }
  44427. }
  44428. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44429. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44430. vertexAttribPointer(
  44431. programAttribute.location + i,
  44432. size / programAttribute.locationSize,
  44433. type,
  44434. normalized,
  44435. stride * bytesPerElement,
  44436. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44437. integer
  44438. );
  44439. }
  44440. } else {
  44441. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44442. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44443. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44444. }
  44445. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44446. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44447. }
  44448. } else {
  44449. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44450. enableAttribute( programAttribute.location + i );
  44451. }
  44452. }
  44453. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44454. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44455. vertexAttribPointer(
  44456. programAttribute.location + i,
  44457. size / programAttribute.locationSize,
  44458. type,
  44459. normalized,
  44460. size * bytesPerElement,
  44461. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44462. integer
  44463. );
  44464. }
  44465. }
  44466. } else if ( materialDefaultAttributeValues !== undefined ) {
  44467. const value = materialDefaultAttributeValues[ name ];
  44468. if ( value !== undefined ) {
  44469. switch ( value.length ) {
  44470. case 2:
  44471. gl.vertexAttrib2fv( programAttribute.location, value );
  44472. break;
  44473. case 3:
  44474. gl.vertexAttrib3fv( programAttribute.location, value );
  44475. break;
  44476. case 4:
  44477. gl.vertexAttrib4fv( programAttribute.location, value );
  44478. break;
  44479. default:
  44480. gl.vertexAttrib1fv( programAttribute.location, value );
  44481. }
  44482. }
  44483. }
  44484. }
  44485. }
  44486. disableUnusedAttributes();
  44487. }
  44488. function dispose() {
  44489. reset();
  44490. for ( const geometryId in bindingStates ) {
  44491. const objectMap = bindingStates[ geometryId ];
  44492. for ( const objectId in objectMap ) {
  44493. const programMap = objectMap[ objectId ];
  44494. for ( const programId in programMap ) {
  44495. const stateMap = programMap[ programId ];
  44496. for ( const wireframe in stateMap ) {
  44497. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44498. delete stateMap[ wireframe ];
  44499. }
  44500. delete programMap[ programId ];
  44501. }
  44502. }
  44503. delete bindingStates[ geometryId ];
  44504. }
  44505. }
  44506. function releaseStatesOfGeometry( geometry ) {
  44507. if ( bindingStates[ geometry.id ] === undefined ) return;
  44508. const objectMap = bindingStates[ geometry.id ];
  44509. for ( const objectId in objectMap ) {
  44510. const programMap = objectMap[ objectId ];
  44511. for ( const programId in programMap ) {
  44512. const stateMap = programMap[ programId ];
  44513. for ( const wireframe in stateMap ) {
  44514. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44515. delete stateMap[ wireframe ];
  44516. }
  44517. delete programMap[ programId ];
  44518. }
  44519. }
  44520. delete bindingStates[ geometry.id ];
  44521. }
  44522. function releaseStatesOfProgram( program ) {
  44523. for ( const geometryId in bindingStates ) {
  44524. const objectMap = bindingStates[ geometryId ];
  44525. for ( const objectId in objectMap ) {
  44526. const programMap = objectMap[ objectId ];
  44527. if ( programMap[ program.id ] === undefined ) continue;
  44528. const stateMap = programMap[ program.id ];
  44529. for ( const wireframe in stateMap ) {
  44530. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44531. delete stateMap[ wireframe ];
  44532. }
  44533. delete programMap[ program.id ];
  44534. }
  44535. }
  44536. }
  44537. function releaseStatesOfObject( object ) {
  44538. for ( const geometryId in bindingStates ) {
  44539. const objectMap = bindingStates[ geometryId ];
  44540. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44541. const programMap = objectMap[ objectId ];
  44542. if ( programMap === undefined ) continue;
  44543. for ( const programId in programMap ) {
  44544. const stateMap = programMap[ programId ];
  44545. for ( const wireframe in stateMap ) {
  44546. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44547. delete stateMap[ wireframe ];
  44548. }
  44549. delete programMap[ programId ];
  44550. }
  44551. delete objectMap[ objectId ];
  44552. if ( Object.keys( objectMap ).length === 0 ) {
  44553. delete bindingStates[ geometryId ];
  44554. }
  44555. }
  44556. }
  44557. function reset() {
  44558. resetDefaultState();
  44559. forceUpdate = true;
  44560. if ( currentState === defaultState ) return;
  44561. currentState = defaultState;
  44562. bindVertexArrayObject( currentState.object );
  44563. }
  44564. // for backward-compatibility
  44565. function resetDefaultState() {
  44566. defaultState.geometry = null;
  44567. defaultState.program = null;
  44568. defaultState.wireframe = false;
  44569. }
  44570. return {
  44571. setup: setup,
  44572. reset: reset,
  44573. resetDefaultState: resetDefaultState,
  44574. dispose: dispose,
  44575. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44576. releaseStatesOfObject: releaseStatesOfObject,
  44577. releaseStatesOfProgram: releaseStatesOfProgram,
  44578. initAttributes: initAttributes,
  44579. enableAttribute: enableAttribute,
  44580. disableUnusedAttributes: disableUnusedAttributes
  44581. };
  44582. }
  44583. function WebGLBufferRenderer( gl, extensions, info ) {
  44584. let mode;
  44585. function setMode( value ) {
  44586. mode = value;
  44587. }
  44588. function render( start, count ) {
  44589. gl.drawArrays( mode, start, count );
  44590. info.update( count, mode, 1 );
  44591. }
  44592. function renderInstances( start, count, primcount ) {
  44593. if ( primcount === 0 ) return;
  44594. gl.drawArraysInstanced( mode, start, count, primcount );
  44595. info.update( count, mode, primcount );
  44596. }
  44597. function renderMultiDraw( starts, counts, drawCount ) {
  44598. if ( drawCount === 0 ) return;
  44599. const extension = extensions.get( 'WEBGL_multi_draw' );
  44600. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44601. let elementCount = 0;
  44602. for ( let i = 0; i < drawCount; i ++ ) {
  44603. elementCount += counts[ i ];
  44604. }
  44605. info.update( elementCount, mode, 1 );
  44606. }
  44607. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44608. if ( drawCount === 0 ) return;
  44609. const extension = extensions.get( 'WEBGL_multi_draw' );
  44610. if ( extension === null ) {
  44611. for ( let i = 0; i < starts.length; i ++ ) {
  44612. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44613. }
  44614. } else {
  44615. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44616. let elementCount = 0;
  44617. for ( let i = 0; i < drawCount; i ++ ) {
  44618. elementCount += counts[ i ] * primcount[ i ];
  44619. }
  44620. info.update( elementCount, mode, 1 );
  44621. }
  44622. }
  44623. //
  44624. this.setMode = setMode;
  44625. this.render = render;
  44626. this.renderInstances = renderInstances;
  44627. this.renderMultiDraw = renderMultiDraw;
  44628. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44629. }
  44630. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44631. let maxAnisotropy;
  44632. function getMaxAnisotropy() {
  44633. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44634. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44635. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44636. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44637. } else {
  44638. maxAnisotropy = 0;
  44639. }
  44640. return maxAnisotropy;
  44641. }
  44642. function textureFormatReadable( textureFormat ) {
  44643. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44644. return false;
  44645. }
  44646. return true;
  44647. }
  44648. function textureTypeReadable( textureType ) {
  44649. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44650. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44651. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44652. return false;
  44653. }
  44654. return true;
  44655. }
  44656. function getMaxPrecision( precision ) {
  44657. if ( precision === 'highp' ) {
  44658. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44659. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44660. return 'highp';
  44661. }
  44662. precision = 'mediump';
  44663. }
  44664. if ( precision === 'mediump' ) {
  44665. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44666. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44667. return 'mediump';
  44668. }
  44669. }
  44670. return 'lowp';
  44671. }
  44672. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44673. const maxPrecision = getMaxPrecision( precision );
  44674. if ( maxPrecision !== precision ) {
  44675. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44676. precision = maxPrecision;
  44677. }
  44678. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44679. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44680. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44681. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44682. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44683. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44684. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44685. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44686. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44687. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44688. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44689. const samples = gl.getParameter( gl.SAMPLES );
  44690. return {
  44691. isWebGL2: true, // keeping this for backwards compatibility
  44692. getMaxAnisotropy: getMaxAnisotropy,
  44693. getMaxPrecision: getMaxPrecision,
  44694. textureFormatReadable: textureFormatReadable,
  44695. textureTypeReadable: textureTypeReadable,
  44696. precision: precision,
  44697. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44698. reversedDepthBuffer: reversedDepthBuffer,
  44699. maxTextures: maxTextures,
  44700. maxVertexTextures: maxVertexTextures,
  44701. maxTextureSize: maxTextureSize,
  44702. maxCubemapSize: maxCubemapSize,
  44703. maxAttributes: maxAttributes,
  44704. maxVertexUniforms: maxVertexUniforms,
  44705. maxVaryings: maxVaryings,
  44706. maxFragmentUniforms: maxFragmentUniforms,
  44707. maxSamples: maxSamples,
  44708. samples: samples
  44709. };
  44710. }
  44711. function WebGLClipping( properties ) {
  44712. const scope = this;
  44713. let globalState = null,
  44714. numGlobalPlanes = 0,
  44715. localClippingEnabled = false,
  44716. renderingShadows = false;
  44717. const plane = new Plane(),
  44718. viewNormalMatrix = new Matrix3(),
  44719. uniform = { value: null, needsUpdate: false };
  44720. this.uniform = uniform;
  44721. this.numPlanes = 0;
  44722. this.numIntersection = 0;
  44723. this.init = function ( planes, enableLocalClipping ) {
  44724. const enabled =
  44725. planes.length !== 0 ||
  44726. enableLocalClipping ||
  44727. // enable state of previous frame - the clipping code has to
  44728. // run another frame in order to reset the state:
  44729. numGlobalPlanes !== 0 ||
  44730. localClippingEnabled;
  44731. localClippingEnabled = enableLocalClipping;
  44732. numGlobalPlanes = planes.length;
  44733. return enabled;
  44734. };
  44735. this.beginShadows = function () {
  44736. renderingShadows = true;
  44737. projectPlanes( null );
  44738. };
  44739. this.endShadows = function () {
  44740. renderingShadows = false;
  44741. };
  44742. this.setGlobalState = function ( planes, camera ) {
  44743. globalState = projectPlanes( planes, camera, 0 );
  44744. };
  44745. this.setState = function ( material, camera, useCache ) {
  44746. const planes = material.clippingPlanes,
  44747. clipIntersection = material.clipIntersection,
  44748. clipShadows = material.clipShadows;
  44749. const materialProperties = properties.get( material );
  44750. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44751. // there's no local clipping
  44752. if ( renderingShadows ) {
  44753. // there's no global clipping
  44754. projectPlanes( null );
  44755. } else {
  44756. resetGlobalState();
  44757. }
  44758. } else {
  44759. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44760. lGlobal = nGlobal * 4;
  44761. let dstArray = materialProperties.clippingState || null;
  44762. uniform.value = dstArray; // ensure unique state
  44763. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44764. for ( let i = 0; i !== lGlobal; ++ i ) {
  44765. dstArray[ i ] = globalState[ i ];
  44766. }
  44767. materialProperties.clippingState = dstArray;
  44768. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44769. this.numPlanes += nGlobal;
  44770. }
  44771. };
  44772. function resetGlobalState() {
  44773. if ( uniform.value !== globalState ) {
  44774. uniform.value = globalState;
  44775. uniform.needsUpdate = numGlobalPlanes > 0;
  44776. }
  44777. scope.numPlanes = numGlobalPlanes;
  44778. scope.numIntersection = 0;
  44779. }
  44780. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44781. const nPlanes = planes !== null ? planes.length : 0;
  44782. let dstArray = null;
  44783. if ( nPlanes !== 0 ) {
  44784. dstArray = uniform.value;
  44785. if ( skipTransform !== true || dstArray === null ) {
  44786. const flatSize = dstOffset + nPlanes * 4,
  44787. viewMatrix = camera.matrixWorldInverse;
  44788. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44789. if ( dstArray === null || dstArray.length < flatSize ) {
  44790. dstArray = new Float32Array( flatSize );
  44791. }
  44792. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44793. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44794. plane.normal.toArray( dstArray, i4 );
  44795. dstArray[ i4 + 3 ] = plane.constant;
  44796. }
  44797. }
  44798. uniform.value = dstArray;
  44799. uniform.needsUpdate = true;
  44800. }
  44801. scope.numPlanes = nPlanes;
  44802. scope.numIntersection = 0;
  44803. return dstArray;
  44804. }
  44805. }
  44806. const LOD_MIN = 4;
  44807. // The standard deviations (radians) associated with the extra mips.
  44808. // Used for scene blur in fromScene() method.
  44809. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44810. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44811. // samples and exit early, but not recompile the shader.
  44812. // Used for scene blur in fromScene() method.
  44813. const MAX_SAMPLES = 20;
  44814. // GGX VNDF importance sampling configuration
  44815. const GGX_SAMPLES = 256;
  44816. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44817. const _clearColor = /*@__PURE__*/ new Color();
  44818. let _oldTarget = null;
  44819. let _oldActiveCubeFace = 0;
  44820. let _oldActiveMipmapLevel = 0;
  44821. let _oldXrEnabled = false;
  44822. const _origin = /*@__PURE__*/ new Vector3();
  44823. /**
  44824. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44825. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44826. * blur to be quickly accessed based on material roughness. It is packed into a
  44827. * special CubeUV format that allows us to perform custom interpolation so that
  44828. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44829. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44830. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44831. * higher roughness levels. In this way we maintain resolution to smoothly
  44832. * interpolate diffuse lighting while limiting sampling computation.
  44833. *
  44834. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44835. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44836. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44837. * used in material rendering for physically-based image-based lighting.
  44838. */
  44839. class PMREMGenerator {
  44840. /**
  44841. * Constructs a new PMREM generator.
  44842. *
  44843. * @param {WebGLRenderer} renderer - The renderer.
  44844. */
  44845. constructor( renderer ) {
  44846. this._renderer = renderer;
  44847. this._pingPongRenderTarget = null;
  44848. this._lodMax = 0;
  44849. this._cubeSize = 0;
  44850. this._sizeLods = [];
  44851. this._sigmas = [];
  44852. this._lodMeshes = [];
  44853. this._backgroundBox = null;
  44854. this._cubemapMaterial = null;
  44855. this._equirectMaterial = null;
  44856. this._blurMaterial = null;
  44857. this._ggxMaterial = null;
  44858. }
  44859. /**
  44860. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44861. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44862. * in radians to be applied to the scene before PMREM generation. Optional near
  44863. * and far planes ensure the scene is rendered in its entirety.
  44864. *
  44865. * @param {Scene} scene - The scene to be captured.
  44866. * @param {number} [sigma=0] - The blur radius in radians.
  44867. * @param {number} [near=0.1] - The near plane distance.
  44868. * @param {number} [far=100] - The far plane distance.
  44869. * @param {Object} [options={}] - The configuration options.
  44870. * @param {number} [options.size=256] - The texture size of the PMREM.
  44871. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44872. * @return {WebGLRenderTarget} The resulting PMREM.
  44873. */
  44874. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44875. const {
  44876. size = 256,
  44877. position = _origin,
  44878. } = options;
  44879. _oldTarget = this._renderer.getRenderTarget();
  44880. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44881. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44882. _oldXrEnabled = this._renderer.xr.enabled;
  44883. this._renderer.xr.enabled = false;
  44884. this._setSize( size );
  44885. const cubeUVRenderTarget = this._allocateTargets();
  44886. cubeUVRenderTarget.depthBuffer = true;
  44887. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44888. if ( sigma > 0 ) {
  44889. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44890. }
  44891. this._applyPMREM( cubeUVRenderTarget );
  44892. this._cleanup( cubeUVRenderTarget );
  44893. return cubeUVRenderTarget;
  44894. }
  44895. /**
  44896. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44897. * or HDR. The ideal input image size is 1k (1024 x 512),
  44898. * as this matches best with the 256 x 256 cubemap output.
  44899. *
  44900. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44901. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44902. * @return {WebGLRenderTarget} The resulting PMREM.
  44903. */
  44904. fromEquirectangular( equirectangular, renderTarget = null ) {
  44905. return this._fromTexture( equirectangular, renderTarget );
  44906. }
  44907. /**
  44908. * Generates a PMREM from an cubemap texture, which can be either LDR
  44909. * or HDR. The ideal input cube size is 256 x 256,
  44910. * as this matches best with the 256 x 256 cubemap output.
  44911. *
  44912. * @param {Texture} cubemap - The cubemap texture to be converted.
  44913. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44914. * @return {WebGLRenderTarget} The resulting PMREM.
  44915. */
  44916. fromCubemap( cubemap, renderTarget = null ) {
  44917. return this._fromTexture( cubemap, renderTarget );
  44918. }
  44919. /**
  44920. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44921. * your texture's network fetch for increased concurrency.
  44922. */
  44923. compileCubemapShader() {
  44924. if ( this._cubemapMaterial === null ) {
  44925. this._cubemapMaterial = _getCubemapMaterial();
  44926. this._compileMaterial( this._cubemapMaterial );
  44927. }
  44928. }
  44929. /**
  44930. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44931. * your texture's network fetch for increased concurrency.
  44932. */
  44933. compileEquirectangularShader() {
  44934. if ( this._equirectMaterial === null ) {
  44935. this._equirectMaterial = _getEquirectMaterial();
  44936. this._compileMaterial( this._equirectMaterial );
  44937. }
  44938. }
  44939. /**
  44940. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44941. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44942. * one of them will cause any others to also become unusable.
  44943. */
  44944. dispose() {
  44945. this._dispose();
  44946. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44947. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44948. if ( this._backgroundBox !== null ) {
  44949. this._backgroundBox.geometry.dispose();
  44950. this._backgroundBox.material.dispose();
  44951. }
  44952. }
  44953. // private interface
  44954. _setSize( cubeSize ) {
  44955. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44956. this._cubeSize = Math.pow( 2, this._lodMax );
  44957. }
  44958. _dispose() {
  44959. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44960. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44961. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44962. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44963. this._lodMeshes[ i ].geometry.dispose();
  44964. }
  44965. }
  44966. _cleanup( outputTarget ) {
  44967. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44968. this._renderer.xr.enabled = _oldXrEnabled;
  44969. outputTarget.scissorTest = false;
  44970. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44971. }
  44972. _fromTexture( texture, renderTarget ) {
  44973. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44974. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44975. } else { // Equirectangular
  44976. this._setSize( texture.image.width / 4 );
  44977. }
  44978. _oldTarget = this._renderer.getRenderTarget();
  44979. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44980. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44981. _oldXrEnabled = this._renderer.xr.enabled;
  44982. this._renderer.xr.enabled = false;
  44983. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44984. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44985. this._applyPMREM( cubeUVRenderTarget );
  44986. this._cleanup( cubeUVRenderTarget );
  44987. return cubeUVRenderTarget;
  44988. }
  44989. _allocateTargets() {
  44990. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44991. const height = 4 * this._cubeSize;
  44992. const params = {
  44993. magFilter: LinearFilter,
  44994. minFilter: LinearFilter,
  44995. generateMipmaps: false,
  44996. type: HalfFloatType,
  44997. format: RGBAFormat,
  44998. colorSpace: LinearSRGBColorSpace,
  44999. depthBuffer: false
  45000. };
  45001. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  45002. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  45003. if ( this._pingPongRenderTarget !== null ) {
  45004. this._dispose();
  45005. }
  45006. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  45007. const { _lodMax } = this;
  45008. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  45009. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  45010. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  45011. }
  45012. return cubeUVRenderTarget;
  45013. }
  45014. _compileMaterial( material ) {
  45015. const mesh = new Mesh( new BufferGeometry(), material );
  45016. this._renderer.compile( mesh, _flatCamera );
  45017. }
  45018. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  45019. const fov = 90;
  45020. const aspect = 1;
  45021. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  45022. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  45023. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  45024. const renderer = this._renderer;
  45025. const originalAutoClear = renderer.autoClear;
  45026. const toneMapping = renderer.toneMapping;
  45027. renderer.getClearColor( _clearColor );
  45028. renderer.toneMapping = NoToneMapping;
  45029. renderer.autoClear = false;
  45030. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  45031. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  45032. if ( reversedDepthBuffer ) {
  45033. renderer.setRenderTarget( cubeUVRenderTarget );
  45034. renderer.clearDepth();
  45035. renderer.setRenderTarget( null );
  45036. }
  45037. if ( this._backgroundBox === null ) {
  45038. this._backgroundBox = new Mesh(
  45039. new BoxGeometry(),
  45040. new MeshBasicMaterial( {
  45041. name: 'PMREM.Background',
  45042. side: BackSide,
  45043. depthWrite: false,
  45044. depthTest: false,
  45045. } )
  45046. );
  45047. }
  45048. const backgroundBox = this._backgroundBox;
  45049. const backgroundMaterial = backgroundBox.material;
  45050. let useSolidColor = false;
  45051. const background = scene.background;
  45052. if ( background ) {
  45053. if ( background.isColor ) {
  45054. backgroundMaterial.color.copy( background );
  45055. scene.background = null;
  45056. useSolidColor = true;
  45057. }
  45058. } else {
  45059. backgroundMaterial.color.copy( _clearColor );
  45060. useSolidColor = true;
  45061. }
  45062. for ( let i = 0; i < 6; i ++ ) {
  45063. const col = i % 3;
  45064. if ( col === 0 ) {
  45065. cubeCamera.up.set( 0, upSign[ i ], 0 );
  45066. cubeCamera.position.set( position.x, position.y, position.z );
  45067. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  45068. } else if ( col === 1 ) {
  45069. cubeCamera.up.set( 0, 0, upSign[ i ] );
  45070. cubeCamera.position.set( position.x, position.y, position.z );
  45071. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  45072. } else {
  45073. cubeCamera.up.set( 0, upSign[ i ], 0 );
  45074. cubeCamera.position.set( position.x, position.y, position.z );
  45075. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  45076. }
  45077. const size = this._cubeSize;
  45078. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  45079. renderer.setRenderTarget( cubeUVRenderTarget );
  45080. if ( useSolidColor ) {
  45081. renderer.render( backgroundBox, cubeCamera );
  45082. }
  45083. renderer.render( scene, cubeCamera );
  45084. }
  45085. renderer.toneMapping = toneMapping;
  45086. renderer.autoClear = originalAutoClear;
  45087. scene.background = background;
  45088. }
  45089. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  45090. const renderer = this._renderer;
  45091. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  45092. if ( isCubeTexture ) {
  45093. if ( this._cubemapMaterial === null ) {
  45094. this._cubemapMaterial = _getCubemapMaterial();
  45095. }
  45096. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  45097. } else {
  45098. if ( this._equirectMaterial === null ) {
  45099. this._equirectMaterial = _getEquirectMaterial();
  45100. }
  45101. }
  45102. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  45103. const mesh = this._lodMeshes[ 0 ];
  45104. mesh.material = material;
  45105. const uniforms = material.uniforms;
  45106. uniforms[ 'envMap' ].value = texture;
  45107. const size = this._cubeSize;
  45108. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  45109. renderer.setRenderTarget( cubeUVRenderTarget );
  45110. renderer.render( mesh, _flatCamera );
  45111. }
  45112. _applyPMREM( cubeUVRenderTarget ) {
  45113. const renderer = this._renderer;
  45114. const autoClear = renderer.autoClear;
  45115. renderer.autoClear = false;
  45116. const n = this._lodMeshes.length;
  45117. // Use GGX VNDF importance sampling
  45118. for ( let i = 1; i < n; i ++ ) {
  45119. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  45120. }
  45121. renderer.autoClear = autoClear;
  45122. }
  45123. /**
  45124. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  45125. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  45126. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  45127. * applies incremental roughness filtering to avoid over-blurring.
  45128. *
  45129. * @private
  45130. * @param {WebGLRenderTarget} cubeUVRenderTarget
  45131. * @param {number} lodIn - Source LOD level to read from
  45132. * @param {number} lodOut - Target LOD level to write to
  45133. */
  45134. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  45135. const renderer = this._renderer;
  45136. const pingPongRenderTarget = this._pingPongRenderTarget;
  45137. const ggxMaterial = this._ggxMaterial;
  45138. const ggxMesh = this._lodMeshes[ lodOut ];
  45139. ggxMesh.material = ggxMaterial;
  45140. const ggxUniforms = ggxMaterial.uniforms;
  45141. // Calculate incremental roughness between LOD levels
  45142. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  45143. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  45144. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  45145. // Apply blur strength mapping for better quality across the roughness range
  45146. const blurStrength = 0.0 + targetRoughness * 1.25;
  45147. const adjustedRoughness = incrementalRoughness * blurStrength;
  45148. // Calculate viewport position based on output LOD level
  45149. const { _lodMax } = this;
  45150. const outputSize = this._sizeLods[ lodOut ];
  45151. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45152. const y = 4 * ( this._cubeSize - outputSize );
  45153. // Read from previous LOD with incremental roughness
  45154. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  45155. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  45156. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  45157. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  45158. renderer.setRenderTarget( pingPongRenderTarget );
  45159. renderer.render( ggxMesh, _flatCamera );
  45160. // Copy from pingPong back to cubeUV (simple direct copy)
  45161. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  45162. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  45163. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  45164. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  45165. renderer.setRenderTarget( cubeUVRenderTarget );
  45166. renderer.render( ggxMesh, _flatCamera );
  45167. }
  45168. /**
  45169. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  45170. * vertically and horizontally, but this breaks down on a cube. Here we apply
  45171. * the blur latitudinally (around the poles), and then longitudinally (towards
  45172. * the poles) to approximate the orthogonally-separable blur. It is least
  45173. * accurate at the poles, but still does a decent job.
  45174. *
  45175. * Used for initial scene blur in fromScene() method when sigma > 0.
  45176. *
  45177. * @private
  45178. * @param {WebGLRenderTarget} cubeUVRenderTarget
  45179. * @param {number} lodIn
  45180. * @param {number} lodOut
  45181. * @param {number} sigma
  45182. * @param {Vector3} [poleAxis]
  45183. */
  45184. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  45185. const pingPongRenderTarget = this._pingPongRenderTarget;
  45186. this._halfBlur(
  45187. cubeUVRenderTarget,
  45188. pingPongRenderTarget,
  45189. lodIn,
  45190. lodOut,
  45191. sigma,
  45192. 'latitudinal',
  45193. poleAxis );
  45194. this._halfBlur(
  45195. pingPongRenderTarget,
  45196. cubeUVRenderTarget,
  45197. lodOut,
  45198. lodOut,
  45199. sigma,
  45200. 'longitudinal',
  45201. poleAxis );
  45202. }
  45203. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  45204. const renderer = this._renderer;
  45205. const blurMaterial = this._blurMaterial;
  45206. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  45207. error(
  45208. 'blur direction must be either latitudinal or longitudinal!' );
  45209. }
  45210. // Number of standard deviations at which to cut off the discrete approximation.
  45211. const STANDARD_DEVIATIONS = 3;
  45212. const blurMesh = this._lodMeshes[ lodOut ];
  45213. blurMesh.material = blurMaterial;
  45214. const blurUniforms = blurMaterial.uniforms;
  45215. const pixels = this._sizeLods[ lodIn ] - 1;
  45216. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  45217. const sigmaPixels = sigmaRadians / radiansPerPixel;
  45218. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  45219. if ( samples > MAX_SAMPLES ) {
  45220. warn( `sigmaRadians, ${
  45221. sigmaRadians}, is too large and will clip, as it requested ${
  45222. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  45223. }
  45224. const weights = [];
  45225. let sum = 0;
  45226. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  45227. const x = i / sigmaPixels;
  45228. const weight = Math.exp( - x * x / 2 );
  45229. weights.push( weight );
  45230. if ( i === 0 ) {
  45231. sum += weight;
  45232. } else if ( i < samples ) {
  45233. sum += 2 * weight;
  45234. }
  45235. }
  45236. for ( let i = 0; i < weights.length; i ++ ) {
  45237. weights[ i ] = weights[ i ] / sum;
  45238. }
  45239. blurUniforms[ 'envMap' ].value = targetIn.texture;
  45240. blurUniforms[ 'samples' ].value = samples;
  45241. blurUniforms[ 'weights' ].value = weights;
  45242. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  45243. if ( poleAxis ) {
  45244. blurUniforms[ 'poleAxis' ].value = poleAxis;
  45245. }
  45246. const { _lodMax } = this;
  45247. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  45248. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  45249. const outputSize = this._sizeLods[ lodOut ];
  45250. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45251. const y = 4 * ( this._cubeSize - outputSize );
  45252. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  45253. renderer.setRenderTarget( targetOut );
  45254. renderer.render( blurMesh, _flatCamera );
  45255. }
  45256. }
  45257. function _createPlanes( lodMax ) {
  45258. const sizeLods = [];
  45259. const sigmas = [];
  45260. const lodMeshes = [];
  45261. let lod = lodMax;
  45262. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  45263. for ( let i = 0; i < totalLods; i ++ ) {
  45264. const sizeLod = Math.pow( 2, lod );
  45265. sizeLods.push( sizeLod );
  45266. let sigma = 1.0 / sizeLod;
  45267. if ( i > lodMax - LOD_MIN ) {
  45268. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  45269. } else if ( i === 0 ) {
  45270. sigma = 0;
  45271. }
  45272. sigmas.push( sigma );
  45273. const texelSize = 1.0 / ( sizeLod - 2 );
  45274. const min = - texelSize;
  45275. const max = 1 + texelSize;
  45276. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  45277. const cubeFaces = 6;
  45278. const vertices = 6;
  45279. const positionSize = 3;
  45280. const uvSize = 2;
  45281. const faceIndexSize = 1;
  45282. const position = new Float32Array( positionSize * vertices * cubeFaces );
  45283. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  45284. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  45285. for ( let face = 0; face < cubeFaces; face ++ ) {
  45286. const x = ( face % 3 ) * 2 / 3 - 1;
  45287. const y = face > 2 ? 0 : -1;
  45288. const coordinates = [
  45289. x, y, 0,
  45290. x + 2 / 3, y, 0,
  45291. x + 2 / 3, y + 1, 0,
  45292. x, y, 0,
  45293. x + 2 / 3, y + 1, 0,
  45294. x, y + 1, 0
  45295. ];
  45296. position.set( coordinates, positionSize * vertices * face );
  45297. uv.set( uv1, uvSize * vertices * face );
  45298. const fill = [ face, face, face, face, face, face ];
  45299. faceIndex.set( fill, faceIndexSize * vertices * face );
  45300. }
  45301. const planes = new BufferGeometry();
  45302. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  45303. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  45304. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  45305. lodMeshes.push( new Mesh( planes, null ) );
  45306. if ( lod > LOD_MIN ) {
  45307. lod --;
  45308. }
  45309. }
  45310. return { lodMeshes, sizeLods, sigmas };
  45311. }
  45312. function _createRenderTarget( width, height, params ) {
  45313. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  45314. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  45315. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  45316. cubeUVRenderTarget.scissorTest = true;
  45317. return cubeUVRenderTarget;
  45318. }
  45319. function _setViewport( target, x, y, width, height ) {
  45320. target.viewport.set( x, y, width, height );
  45321. target.scissor.set( x, y, width, height );
  45322. }
  45323. function _getGGXShader( lodMax, width, height ) {
  45324. const shaderMaterial = new ShaderMaterial( {
  45325. name: 'PMREMGGXConvolution',
  45326. defines: {
  45327. 'GGX_SAMPLES': GGX_SAMPLES,
  45328. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45329. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45330. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45331. },
  45332. uniforms: {
  45333. 'envMap': { value: null },
  45334. 'roughness': { value: 0.0 },
  45335. 'mipInt': { value: 0 }
  45336. },
  45337. vertexShader: _getCommonVertexShader(),
  45338. fragmentShader: /* glsl */`
  45339. precision highp float;
  45340. precision highp int;
  45341. varying vec3 vOutputDirection;
  45342. uniform sampler2D envMap;
  45343. uniform float roughness;
  45344. uniform float mipInt;
  45345. #define ENVMAP_TYPE_CUBE_UV
  45346. #include <cube_uv_reflection_fragment>
  45347. #define PI 3.14159265359
  45348. // Van der Corput radical inverse
  45349. float radicalInverse_VdC(uint bits) {
  45350. bits = (bits << 16u) | (bits >> 16u);
  45351. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  45352. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  45353. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  45354. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  45355. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  45356. }
  45357. // Hammersley sequence
  45358. vec2 hammersley(uint i, uint N) {
  45359. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  45360. }
  45361. // GGX VNDF importance sampling (Eric Heitz 2018)
  45362. // "Sampling the GGX Distribution of Visible Normals"
  45363. // https://jcgt.org/published/0007/04/01/
  45364. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  45365. float alpha = roughness * roughness;
  45366. // Section 4.1: Orthonormal basis
  45367. vec3 T1 = vec3(1.0, 0.0, 0.0);
  45368. vec3 T2 = cross(V, T1);
  45369. // Section 4.2: Parameterization of projected area
  45370. float r = sqrt(Xi.x);
  45371. float phi = 2.0 * PI * Xi.y;
  45372. float t1 = r * cos(phi);
  45373. float t2 = r * sin(phi);
  45374. float s = 0.5 * (1.0 + V.z);
  45375. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45376. // Section 4.3: Reprojection onto hemisphere
  45377. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;
  45378. // Section 3.4: Transform back to ellipsoid configuration
  45379. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45380. }
  45381. void main() {
  45382. vec3 N = normalize(vOutputDirection);
  45383. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45384. vec3 prefilteredColor = vec3(0.0);
  45385. float totalWeight = 0.0;
  45386. // For very low roughness, just sample the environment directly
  45387. if (roughness < 0.001) {
  45388. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45389. return;
  45390. }
  45391. // Tangent space basis for VNDF sampling
  45392. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45393. vec3 tangent = normalize(cross(up, N));
  45394. vec3 bitangent = cross(N, tangent);
  45395. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45396. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45397. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45398. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45399. // Transform H back to world space
  45400. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45401. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45402. float NdotL = max(dot(N, L), 0.0);
  45403. if(NdotL > 0.0) {
  45404. // Sample environment at fixed mip level
  45405. // VNDF importance sampling handles the distribution filtering
  45406. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45407. // Weight by NdotL for the split-sum approximation
  45408. // VNDF PDF naturally accounts for the visible microfacet distribution
  45409. prefilteredColor += sampleColor * NdotL;
  45410. totalWeight += NdotL;
  45411. }
  45412. }
  45413. if (totalWeight > 0.0) {
  45414. prefilteredColor = prefilteredColor / totalWeight;
  45415. }
  45416. gl_FragColor = vec4(prefilteredColor, 1.0);
  45417. }
  45418. `,
  45419. blending: NoBlending,
  45420. depthTest: false,
  45421. depthWrite: false
  45422. } );
  45423. return shaderMaterial;
  45424. }
  45425. function _getBlurShader( lodMax, width, height ) {
  45426. const weights = new Float32Array( MAX_SAMPLES );
  45427. const poleAxis = new Vector3( 0, 1, 0 );
  45428. const shaderMaterial = new ShaderMaterial( {
  45429. name: 'SphericalGaussianBlur',
  45430. defines: {
  45431. 'n': MAX_SAMPLES,
  45432. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45433. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45434. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45435. },
  45436. uniforms: {
  45437. 'envMap': { value: null },
  45438. 'samples': { value: 1 },
  45439. 'weights': { value: weights },
  45440. 'latitudinal': { value: false },
  45441. 'dTheta': { value: 0 },
  45442. 'mipInt': { value: 0 },
  45443. 'poleAxis': { value: poleAxis }
  45444. },
  45445. vertexShader: _getCommonVertexShader(),
  45446. fragmentShader: /* glsl */`
  45447. precision mediump float;
  45448. precision mediump int;
  45449. varying vec3 vOutputDirection;
  45450. uniform sampler2D envMap;
  45451. uniform int samples;
  45452. uniform float weights[ n ];
  45453. uniform bool latitudinal;
  45454. uniform float dTheta;
  45455. uniform float mipInt;
  45456. uniform vec3 poleAxis;
  45457. #define ENVMAP_TYPE_CUBE_UV
  45458. #include <cube_uv_reflection_fragment>
  45459. vec3 getSample( float theta, vec3 axis ) {
  45460. float cosTheta = cos( theta );
  45461. // Rodrigues' axis-angle rotation
  45462. vec3 sampleDirection = vOutputDirection * cosTheta
  45463. + cross( axis, vOutputDirection ) * sin( theta )
  45464. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45465. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45466. }
  45467. void main() {
  45468. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45469. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45470. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45471. }
  45472. axis = normalize( axis );
  45473. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45474. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45475. for ( int i = 1; i < n; i++ ) {
  45476. if ( i >= samples ) {
  45477. break;
  45478. }
  45479. float theta = dTheta * float( i );
  45480. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45481. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45482. }
  45483. }
  45484. `,
  45485. blending: NoBlending,
  45486. depthTest: false,
  45487. depthWrite: false
  45488. } );
  45489. return shaderMaterial;
  45490. }
  45491. function _getEquirectMaterial() {
  45492. return new ShaderMaterial( {
  45493. name: 'EquirectangularToCubeUV',
  45494. uniforms: {
  45495. 'envMap': { value: null }
  45496. },
  45497. vertexShader: _getCommonVertexShader(),
  45498. fragmentShader: /* glsl */`
  45499. precision mediump float;
  45500. precision mediump int;
  45501. varying vec3 vOutputDirection;
  45502. uniform sampler2D envMap;
  45503. #include <common>
  45504. void main() {
  45505. vec3 outputDirection = normalize( vOutputDirection );
  45506. vec2 uv = equirectUv( outputDirection );
  45507. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45508. }
  45509. `,
  45510. blending: NoBlending,
  45511. depthTest: false,
  45512. depthWrite: false
  45513. } );
  45514. }
  45515. function _getCubemapMaterial() {
  45516. return new ShaderMaterial( {
  45517. name: 'CubemapToCubeUV',
  45518. uniforms: {
  45519. 'envMap': { value: null },
  45520. 'flipEnvMap': { value: -1 }
  45521. },
  45522. vertexShader: _getCommonVertexShader(),
  45523. fragmentShader: /* glsl */`
  45524. precision mediump float;
  45525. precision mediump int;
  45526. uniform float flipEnvMap;
  45527. varying vec3 vOutputDirection;
  45528. uniform samplerCube envMap;
  45529. void main() {
  45530. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45531. }
  45532. `,
  45533. blending: NoBlending,
  45534. depthTest: false,
  45535. depthWrite: false
  45536. } );
  45537. }
  45538. function _getCommonVertexShader() {
  45539. return /* glsl */`
  45540. precision mediump float;
  45541. precision mediump int;
  45542. attribute float faceIndex;
  45543. varying vec3 vOutputDirection;
  45544. // RH coordinate system; PMREM face-indexing convention
  45545. vec3 getDirection( vec2 uv, float face ) {
  45546. uv = 2.0 * uv - 1.0;
  45547. vec3 direction = vec3( uv, 1.0 );
  45548. if ( face == 0.0 ) {
  45549. direction = direction.zyx; // ( 1, v, u ) pos x
  45550. } else if ( face == 1.0 ) {
  45551. direction = direction.xzy;
  45552. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45553. } else if ( face == 2.0 ) {
  45554. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45555. } else if ( face == 3.0 ) {
  45556. direction = direction.zyx;
  45557. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45558. } else if ( face == 4.0 ) {
  45559. direction = direction.xzy;
  45560. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45561. } else if ( face == 5.0 ) {
  45562. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45563. }
  45564. return direction;
  45565. }
  45566. void main() {
  45567. vOutputDirection = getDirection( uv, faceIndex );
  45568. gl_Position = vec4( position, 1.0 );
  45569. }
  45570. `;
  45571. }
  45572. function WebGLEnvironments( renderer ) {
  45573. let cubeMaps = new WeakMap();
  45574. let pmremMaps = new WeakMap();
  45575. let pmremGenerator = null;
  45576. function get( texture, usePMREM = false ) {
  45577. if ( texture === null || texture === undefined ) return null;
  45578. if ( usePMREM ) {
  45579. return getPMREM( texture );
  45580. }
  45581. return getCube( texture );
  45582. }
  45583. function getCube( texture ) {
  45584. if ( texture && texture.isTexture ) {
  45585. const mapping = texture.mapping;
  45586. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  45587. if ( cubeMaps.has( texture ) ) {
  45588. const cubemap = cubeMaps.get( texture ).texture;
  45589. return mapTextureMapping( cubemap, texture.mapping );
  45590. } else {
  45591. const image = texture.image;
  45592. if ( image && image.height > 0 ) {
  45593. const renderTarget = new WebGLCubeRenderTarget( image.height );
  45594. renderTarget.fromEquirectangularTexture( renderer, texture );
  45595. cubeMaps.set( texture, renderTarget );
  45596. texture.addEventListener( 'dispose', onCubemapDispose );
  45597. return mapTextureMapping( renderTarget.texture, texture.mapping );
  45598. } else {
  45599. // image not yet ready. try the conversion next frame
  45600. return null;
  45601. }
  45602. }
  45603. }
  45604. }
  45605. return texture;
  45606. }
  45607. function getPMREM( texture ) {
  45608. if ( texture && texture.isTexture ) {
  45609. const mapping = texture.mapping;
  45610. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45611. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45612. // equirect/cube map to cubeUV conversion
  45613. if ( isEquirectMap || isCubeMap ) {
  45614. let renderTarget = pmremMaps.get( texture );
  45615. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45616. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45617. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45618. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45619. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45620. pmremMaps.set( texture, renderTarget );
  45621. return renderTarget.texture;
  45622. } else {
  45623. if ( renderTarget !== undefined ) {
  45624. return renderTarget.texture;
  45625. } else {
  45626. const image = texture.image;
  45627. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45628. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45629. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45630. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45631. pmremMaps.set( texture, renderTarget );
  45632. texture.addEventListener( 'dispose', onPMREMDispose );
  45633. return renderTarget.texture;
  45634. } else {
  45635. // image not yet ready. try the conversion next frame
  45636. return null;
  45637. }
  45638. }
  45639. }
  45640. }
  45641. }
  45642. return texture;
  45643. }
  45644. function mapTextureMapping( texture, mapping ) {
  45645. if ( mapping === EquirectangularReflectionMapping ) {
  45646. texture.mapping = CubeReflectionMapping;
  45647. } else if ( mapping === EquirectangularRefractionMapping ) {
  45648. texture.mapping = CubeRefractionMapping;
  45649. }
  45650. return texture;
  45651. }
  45652. function isCubeTextureComplete( image ) {
  45653. let count = 0;
  45654. const length = 6;
  45655. for ( let i = 0; i < length; i ++ ) {
  45656. if ( image[ i ] !== undefined ) count ++;
  45657. }
  45658. return count === length;
  45659. }
  45660. function onCubemapDispose( event ) {
  45661. const texture = event.target;
  45662. texture.removeEventListener( 'dispose', onCubemapDispose );
  45663. const cubemap = cubeMaps.get( texture );
  45664. if ( cubemap !== undefined ) {
  45665. cubeMaps.delete( texture );
  45666. cubemap.dispose();
  45667. }
  45668. }
  45669. function onPMREMDispose( event ) {
  45670. const texture = event.target;
  45671. texture.removeEventListener( 'dispose', onPMREMDispose );
  45672. const pmrem = pmremMaps.get( texture );
  45673. if ( pmrem !== undefined ) {
  45674. pmremMaps.delete( texture );
  45675. pmrem.dispose();
  45676. }
  45677. }
  45678. function dispose() {
  45679. cubeMaps = new WeakMap();
  45680. pmremMaps = new WeakMap();
  45681. if ( pmremGenerator !== null ) {
  45682. pmremGenerator.dispose();
  45683. pmremGenerator = null;
  45684. }
  45685. }
  45686. return {
  45687. get: get,
  45688. dispose: dispose
  45689. };
  45690. }
  45691. function WebGLExtensions( gl ) {
  45692. const extensions = {};
  45693. function getExtension( name ) {
  45694. if ( extensions[ name ] !== undefined ) {
  45695. return extensions[ name ];
  45696. }
  45697. const extension = gl.getExtension( name );
  45698. extensions[ name ] = extension;
  45699. return extension;
  45700. }
  45701. return {
  45702. has: function ( name ) {
  45703. return getExtension( name ) !== null;
  45704. },
  45705. init: function () {
  45706. getExtension( 'EXT_color_buffer_float' );
  45707. getExtension( 'WEBGL_clip_cull_distance' );
  45708. getExtension( 'OES_texture_float_linear' );
  45709. getExtension( 'EXT_color_buffer_half_float' );
  45710. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45711. getExtension( 'WEBGL_render_shared_exponent' );
  45712. },
  45713. get: function ( name ) {
  45714. const extension = getExtension( name );
  45715. if ( extension === null ) {
  45716. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45717. }
  45718. return extension;
  45719. }
  45720. };
  45721. }
  45722. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45723. const geometries = {};
  45724. const wireframeAttributes = new WeakMap();
  45725. function onGeometryDispose( event ) {
  45726. const geometry = event.target;
  45727. if ( geometry.index !== null ) {
  45728. attributes.remove( geometry.index );
  45729. }
  45730. for ( const name in geometry.attributes ) {
  45731. attributes.remove( geometry.attributes[ name ] );
  45732. }
  45733. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45734. delete geometries[ geometry.id ];
  45735. const attribute = wireframeAttributes.get( geometry );
  45736. if ( attribute ) {
  45737. attributes.remove( attribute );
  45738. wireframeAttributes.delete( geometry );
  45739. }
  45740. bindingStates.releaseStatesOfGeometry( geometry );
  45741. if ( geometry.isInstancedBufferGeometry === true ) {
  45742. delete geometry._maxInstanceCount;
  45743. }
  45744. //
  45745. info.memory.geometries --;
  45746. }
  45747. function get( object, geometry ) {
  45748. if ( geometries[ geometry.id ] === true ) return geometry;
  45749. geometry.addEventListener( 'dispose', onGeometryDispose );
  45750. geometries[ geometry.id ] = true;
  45751. info.memory.geometries ++;
  45752. return geometry;
  45753. }
  45754. function update( geometry ) {
  45755. const geometryAttributes = geometry.attributes;
  45756. // Updating index buffer in VAO now. See WebGLBindingStates.
  45757. for ( const name in geometryAttributes ) {
  45758. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45759. }
  45760. }
  45761. function updateWireframeAttribute( geometry ) {
  45762. const indices = [];
  45763. const geometryIndex = geometry.index;
  45764. const geometryPosition = geometry.attributes.position;
  45765. let version = 0;
  45766. if ( geometryIndex !== null ) {
  45767. const array = geometryIndex.array;
  45768. version = geometryIndex.version;
  45769. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45770. const a = array[ i + 0 ];
  45771. const b = array[ i + 1 ];
  45772. const c = array[ i + 2 ];
  45773. indices.push( a, b, b, c, c, a );
  45774. }
  45775. } else if ( geometryPosition !== undefined ) {
  45776. const array = geometryPosition.array;
  45777. version = geometryPosition.version;
  45778. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45779. const a = i + 0;
  45780. const b = i + 1;
  45781. const c = i + 2;
  45782. indices.push( a, b, b, c, c, a );
  45783. }
  45784. } else {
  45785. return;
  45786. }
  45787. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45788. attribute.version = version;
  45789. // Updating index buffer in VAO now. See WebGLBindingStates
  45790. //
  45791. const previousAttribute = wireframeAttributes.get( geometry );
  45792. if ( previousAttribute ) attributes.remove( previousAttribute );
  45793. //
  45794. wireframeAttributes.set( geometry, attribute );
  45795. }
  45796. function getWireframeAttribute( geometry ) {
  45797. const currentAttribute = wireframeAttributes.get( geometry );
  45798. if ( currentAttribute ) {
  45799. const geometryIndex = geometry.index;
  45800. if ( geometryIndex !== null ) {
  45801. // if the attribute is obsolete, create a new one
  45802. if ( currentAttribute.version < geometryIndex.version ) {
  45803. updateWireframeAttribute( geometry );
  45804. }
  45805. }
  45806. } else {
  45807. updateWireframeAttribute( geometry );
  45808. }
  45809. return wireframeAttributes.get( geometry );
  45810. }
  45811. return {
  45812. get: get,
  45813. update: update,
  45814. getWireframeAttribute: getWireframeAttribute
  45815. };
  45816. }
  45817. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45818. let mode;
  45819. function setMode( value ) {
  45820. mode = value;
  45821. }
  45822. let type, bytesPerElement;
  45823. function setIndex( value ) {
  45824. type = value.type;
  45825. bytesPerElement = value.bytesPerElement;
  45826. }
  45827. function render( start, count ) {
  45828. gl.drawElements( mode, count, type, start * bytesPerElement );
  45829. info.update( count, mode, 1 );
  45830. }
  45831. function renderInstances( start, count, primcount ) {
  45832. if ( primcount === 0 ) return;
  45833. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45834. info.update( count, mode, primcount );
  45835. }
  45836. function renderMultiDraw( starts, counts, drawCount ) {
  45837. if ( drawCount === 0 ) return;
  45838. const extension = extensions.get( 'WEBGL_multi_draw' );
  45839. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45840. let elementCount = 0;
  45841. for ( let i = 0; i < drawCount; i ++ ) {
  45842. elementCount += counts[ i ];
  45843. }
  45844. info.update( elementCount, mode, 1 );
  45845. }
  45846. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45847. if ( drawCount === 0 ) return;
  45848. const extension = extensions.get( 'WEBGL_multi_draw' );
  45849. if ( extension === null ) {
  45850. for ( let i = 0; i < starts.length; i ++ ) {
  45851. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45852. }
  45853. } else {
  45854. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45855. let elementCount = 0;
  45856. for ( let i = 0; i < drawCount; i ++ ) {
  45857. elementCount += counts[ i ] * primcount[ i ];
  45858. }
  45859. info.update( elementCount, mode, 1 );
  45860. }
  45861. }
  45862. //
  45863. this.setMode = setMode;
  45864. this.setIndex = setIndex;
  45865. this.render = render;
  45866. this.renderInstances = renderInstances;
  45867. this.renderMultiDraw = renderMultiDraw;
  45868. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45869. }
  45870. function WebGLInfo( gl ) {
  45871. const memory = {
  45872. geometries: 0,
  45873. textures: 0
  45874. };
  45875. const render = {
  45876. frame: 0,
  45877. calls: 0,
  45878. triangles: 0,
  45879. points: 0,
  45880. lines: 0
  45881. };
  45882. function update( count, mode, instanceCount ) {
  45883. render.calls ++;
  45884. switch ( mode ) {
  45885. case gl.TRIANGLES:
  45886. render.triangles += instanceCount * ( count / 3 );
  45887. break;
  45888. case gl.LINES:
  45889. render.lines += instanceCount * ( count / 2 );
  45890. break;
  45891. case gl.LINE_STRIP:
  45892. render.lines += instanceCount * ( count - 1 );
  45893. break;
  45894. case gl.LINE_LOOP:
  45895. render.lines += instanceCount * count;
  45896. break;
  45897. case gl.POINTS:
  45898. render.points += instanceCount * count;
  45899. break;
  45900. default:
  45901. error( 'WebGLInfo: Unknown draw mode:', mode );
  45902. break;
  45903. }
  45904. }
  45905. function reset() {
  45906. render.calls = 0;
  45907. render.triangles = 0;
  45908. render.points = 0;
  45909. render.lines = 0;
  45910. }
  45911. return {
  45912. memory: memory,
  45913. render: render,
  45914. programs: null,
  45915. autoReset: true,
  45916. reset: reset,
  45917. update: update
  45918. };
  45919. }
  45920. function WebGLMorphtargets( gl, capabilities, textures ) {
  45921. const morphTextures = new WeakMap();
  45922. const morph = new Vector4();
  45923. function update( object, geometry, program ) {
  45924. const objectInfluences = object.morphTargetInfluences;
  45925. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45926. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45927. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45928. let entry = morphTextures.get( geometry );
  45929. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45930. if ( entry !== undefined ) entry.texture.dispose();
  45931. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45932. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45933. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45934. const morphTargets = geometry.morphAttributes.position || [];
  45935. const morphNormals = geometry.morphAttributes.normal || [];
  45936. const morphColors = geometry.morphAttributes.color || [];
  45937. let vertexDataCount = 0;
  45938. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45939. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45940. if ( hasMorphColors === true ) vertexDataCount = 3;
  45941. let width = geometry.attributes.position.count * vertexDataCount;
  45942. let height = 1;
  45943. if ( width > capabilities.maxTextureSize ) {
  45944. height = Math.ceil( width / capabilities.maxTextureSize );
  45945. width = capabilities.maxTextureSize;
  45946. }
  45947. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45948. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45949. texture.type = FloatType;
  45950. texture.needsUpdate = true;
  45951. // fill buffer
  45952. const vertexDataStride = vertexDataCount * 4;
  45953. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45954. const morphTarget = morphTargets[ i ];
  45955. const morphNormal = morphNormals[ i ];
  45956. const morphColor = morphColors[ i ];
  45957. const offset = width * height * 4 * i;
  45958. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45959. const stride = j * vertexDataStride;
  45960. if ( hasMorphPosition === true ) {
  45961. morph.fromBufferAttribute( morphTarget, j );
  45962. buffer[ offset + stride + 0 ] = morph.x;
  45963. buffer[ offset + stride + 1 ] = morph.y;
  45964. buffer[ offset + stride + 2 ] = morph.z;
  45965. buffer[ offset + stride + 3 ] = 0;
  45966. }
  45967. if ( hasMorphNormals === true ) {
  45968. morph.fromBufferAttribute( morphNormal, j );
  45969. buffer[ offset + stride + 4 ] = morph.x;
  45970. buffer[ offset + stride + 5 ] = morph.y;
  45971. buffer[ offset + stride + 6 ] = morph.z;
  45972. buffer[ offset + stride + 7 ] = 0;
  45973. }
  45974. if ( hasMorphColors === true ) {
  45975. morph.fromBufferAttribute( morphColor, j );
  45976. buffer[ offset + stride + 8 ] = morph.x;
  45977. buffer[ offset + stride + 9 ] = morph.y;
  45978. buffer[ offset + stride + 10 ] = morph.z;
  45979. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45980. }
  45981. }
  45982. }
  45983. entry = {
  45984. count: morphTargetsCount,
  45985. texture: texture,
  45986. size: new Vector2( width, height )
  45987. };
  45988. morphTextures.set( geometry, entry );
  45989. function disposeTexture() {
  45990. texture.dispose();
  45991. morphTextures.delete( geometry );
  45992. geometry.removeEventListener( 'dispose', disposeTexture );
  45993. }
  45994. geometry.addEventListener( 'dispose', disposeTexture );
  45995. }
  45996. //
  45997. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45998. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45999. } else {
  46000. let morphInfluencesSum = 0;
  46001. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  46002. morphInfluencesSum += objectInfluences[ i ];
  46003. }
  46004. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  46005. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  46006. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  46007. }
  46008. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  46009. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  46010. }
  46011. return {
  46012. update: update
  46013. };
  46014. }
  46015. function WebGLObjects( gl, geometries, attributes, bindingStates, info ) {
  46016. let updateMap = new WeakMap();
  46017. function update( object ) {
  46018. const frame = info.render.frame;
  46019. const geometry = object.geometry;
  46020. const buffergeometry = geometries.get( object, geometry );
  46021. // Update once per frame
  46022. if ( updateMap.get( buffergeometry ) !== frame ) {
  46023. geometries.update( buffergeometry );
  46024. updateMap.set( buffergeometry, frame );
  46025. }
  46026. if ( object.isInstancedMesh ) {
  46027. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  46028. object.addEventListener( 'dispose', onInstancedMeshDispose );
  46029. }
  46030. if ( updateMap.get( object ) !== frame ) {
  46031. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  46032. if ( object.instanceColor !== null ) {
  46033. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  46034. }
  46035. updateMap.set( object, frame );
  46036. }
  46037. }
  46038. if ( object.isSkinnedMesh ) {
  46039. const skeleton = object.skeleton;
  46040. if ( updateMap.get( skeleton ) !== frame ) {
  46041. skeleton.update();
  46042. updateMap.set( skeleton, frame );
  46043. }
  46044. }
  46045. return buffergeometry;
  46046. }
  46047. function dispose() {
  46048. updateMap = new WeakMap();
  46049. }
  46050. function onInstancedMeshDispose( event ) {
  46051. const instancedMesh = event.target;
  46052. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  46053. bindingStates.releaseStatesOfObject( instancedMesh );
  46054. attributes.remove( instancedMesh.instanceMatrix );
  46055. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  46056. }
  46057. return {
  46058. update: update,
  46059. dispose: dispose
  46060. };
  46061. }
  46062. const toneMappingMap = {
  46063. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  46064. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  46065. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  46066. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  46067. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  46068. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  46069. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  46070. };
  46071. function WebGLOutput( type, width, height, depth, stencil ) {
  46072. // render targets for scene and post-processing
  46073. const targetA = new WebGLRenderTarget( width, height, {
  46074. type: type,
  46075. depthBuffer: depth,
  46076. stencilBuffer: stencil
  46077. } );
  46078. const targetB = new WebGLRenderTarget( width, height, {
  46079. type: HalfFloatType,
  46080. depthBuffer: false,
  46081. stencilBuffer: false
  46082. } );
  46083. // create fullscreen triangle geometry
  46084. const geometry = new BufferGeometry();
  46085. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  46086. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  46087. // create output material with tone mapping support
  46088. const material = new RawShaderMaterial( {
  46089. uniforms: {
  46090. tDiffuse: { value: null }
  46091. },
  46092. vertexShader: /* glsl */`
  46093. precision highp float;
  46094. uniform mat4 modelViewMatrix;
  46095. uniform mat4 projectionMatrix;
  46096. attribute vec3 position;
  46097. attribute vec2 uv;
  46098. varying vec2 vUv;
  46099. void main() {
  46100. vUv = uv;
  46101. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  46102. }`,
  46103. fragmentShader: /* glsl */`
  46104. precision highp float;
  46105. uniform sampler2D tDiffuse;
  46106. varying vec2 vUv;
  46107. #include <tonemapping_pars_fragment>
  46108. #include <colorspace_pars_fragment>
  46109. void main() {
  46110. gl_FragColor = texture2D( tDiffuse, vUv );
  46111. #ifdef LINEAR_TONE_MAPPING
  46112. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  46113. #elif defined( REINHARD_TONE_MAPPING )
  46114. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  46115. #elif defined( CINEON_TONE_MAPPING )
  46116. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  46117. #elif defined( ACES_FILMIC_TONE_MAPPING )
  46118. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  46119. #elif defined( AGX_TONE_MAPPING )
  46120. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  46121. #elif defined( NEUTRAL_TONE_MAPPING )
  46122. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  46123. #elif defined( CUSTOM_TONE_MAPPING )
  46124. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  46125. #endif
  46126. #ifdef SRGB_TRANSFER
  46127. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  46128. #endif
  46129. }`,
  46130. depthTest: false,
  46131. depthWrite: false
  46132. } );
  46133. const mesh = new Mesh( geometry, material );
  46134. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  46135. let _outputColorSpace = null;
  46136. let _outputToneMapping = null;
  46137. let _isCompositing = false;
  46138. let _savedToneMapping;
  46139. let _savedRenderTarget = null;
  46140. let _effects = [];
  46141. let _hasRenderPass = false;
  46142. this.setSize = function ( width, height ) {
  46143. targetA.setSize( width, height );
  46144. targetB.setSize( width, height );
  46145. for ( let i = 0; i < _effects.length; i ++ ) {
  46146. const effect = _effects[ i ];
  46147. if ( effect.setSize ) effect.setSize( width, height );
  46148. }
  46149. };
  46150. this.setEffects = function ( effects ) {
  46151. _effects = effects;
  46152. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  46153. const width = targetA.width;
  46154. const height = targetA.height;
  46155. for ( let i = 0; i < _effects.length; i ++ ) {
  46156. const effect = _effects[ i ];
  46157. if ( effect.setSize ) effect.setSize( width, height );
  46158. }
  46159. };
  46160. this.begin = function ( renderer, renderTarget ) {
  46161. // Don't begin during compositing phase (post-processing effects call render())
  46162. if ( _isCompositing ) return false;
  46163. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  46164. _savedRenderTarget = renderTarget;
  46165. // resize internal buffers to match render target (e.g. XR resolution)
  46166. if ( renderTarget !== null ) {
  46167. const width = renderTarget.width;
  46168. const height = renderTarget.height;
  46169. if ( targetA.width !== width || targetA.height !== height ) {
  46170. this.setSize( width, height );
  46171. }
  46172. }
  46173. // if first effect is a RenderPass, it will set its own render target
  46174. if ( _hasRenderPass === false ) {
  46175. renderer.setRenderTarget( targetA );
  46176. }
  46177. // disable tone mapping during render - it will be applied in end()
  46178. _savedToneMapping = renderer.toneMapping;
  46179. renderer.toneMapping = NoToneMapping;
  46180. return true;
  46181. };
  46182. this.hasRenderPass = function () {
  46183. return _hasRenderPass;
  46184. };
  46185. this.end = function ( renderer, deltaTime ) {
  46186. // restore tone mapping
  46187. renderer.toneMapping = _savedToneMapping;
  46188. _isCompositing = true;
  46189. // run post-processing effects
  46190. let readBuffer = targetA;
  46191. let writeBuffer = targetB;
  46192. for ( let i = 0; i < _effects.length; i ++ ) {
  46193. const effect = _effects[ i ];
  46194. if ( effect.enabled === false ) continue;
  46195. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  46196. if ( effect.needsSwap !== false ) {
  46197. const temp = readBuffer;
  46198. readBuffer = writeBuffer;
  46199. writeBuffer = temp;
  46200. }
  46201. }
  46202. // update output material defines if settings changed
  46203. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  46204. _outputColorSpace = renderer.outputColorSpace;
  46205. _outputToneMapping = renderer.toneMapping;
  46206. material.defines = {};
  46207. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  46208. const toneMapping = toneMappingMap[ _outputToneMapping ];
  46209. if ( toneMapping ) material.defines[ toneMapping ] = '';
  46210. material.needsUpdate = true;
  46211. }
  46212. // final output to canvas (or XR render target)
  46213. material.uniforms.tDiffuse.value = readBuffer.texture;
  46214. renderer.setRenderTarget( _savedRenderTarget );
  46215. renderer.render( mesh, camera );
  46216. _savedRenderTarget = null;
  46217. _isCompositing = false;
  46218. };
  46219. this.isCompositing = function () {
  46220. return _isCompositing;
  46221. };
  46222. this.dispose = function () {
  46223. targetA.dispose();
  46224. targetB.dispose();
  46225. geometry.dispose();
  46226. material.dispose();
  46227. };
  46228. }
  46229. /**
  46230. * Uniforms of a program.
  46231. * Those form a tree structure with a special top-level container for the root,
  46232. * which you get by calling 'new WebGLUniforms( gl, program )'.
  46233. *
  46234. *
  46235. * Properties of inner nodes including the top-level container:
  46236. *
  46237. * .seq - array of nested uniforms
  46238. * .map - nested uniforms by name
  46239. *
  46240. *
  46241. * Methods of all nodes except the top-level container:
  46242. *
  46243. * .setValue( gl, value, [textures] )
  46244. *
  46245. * uploads a uniform value(s)
  46246. * the 'textures' parameter is needed for sampler uniforms
  46247. *
  46248. *
  46249. * Static methods of the top-level container (textures factorizations):
  46250. *
  46251. * .upload( gl, seq, values, textures )
  46252. *
  46253. * sets uniforms in 'seq' to 'values[id].value'
  46254. *
  46255. * .seqWithValue( seq, values ) : filteredSeq
  46256. *
  46257. * filters 'seq' entries with corresponding entry in values
  46258. *
  46259. *
  46260. * Methods of the top-level container (textures factorizations):
  46261. *
  46262. * .setValue( gl, name, value, textures )
  46263. *
  46264. * sets uniform with name 'name' to 'value'
  46265. *
  46266. * .setOptional( gl, obj, prop )
  46267. *
  46268. * like .set for an optional property of the object
  46269. *
  46270. */
  46271. const emptyTexture = /*@__PURE__*/ new Texture();
  46272. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  46273. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  46274. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  46275. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  46276. // --- Utilities ---
  46277. // Array Caches (provide typed arrays for temporary by size)
  46278. const arrayCacheF32 = [];
  46279. const arrayCacheI32 = [];
  46280. // Float32Array caches used for uploading Matrix uniforms
  46281. const mat4array = new Float32Array( 16 );
  46282. const mat3array = new Float32Array( 9 );
  46283. const mat2array = new Float32Array( 4 );
  46284. // Flattening for arrays of vectors and matrices
  46285. function flatten( array, nBlocks, blockSize ) {
  46286. const firstElem = array[ 0 ];
  46287. if ( firstElem <= 0 || firstElem > 0 ) return array;
  46288. // unoptimized: ! isNaN( firstElem )
  46289. // see http://jacksondunstan.com/articles/983
  46290. const n = nBlocks * blockSize;
  46291. let r = arrayCacheF32[ n ];
  46292. if ( r === undefined ) {
  46293. r = new Float32Array( n );
  46294. arrayCacheF32[ n ] = r;
  46295. }
  46296. if ( nBlocks !== 0 ) {
  46297. firstElem.toArray( r, 0 );
  46298. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  46299. offset += blockSize;
  46300. array[ i ].toArray( r, offset );
  46301. }
  46302. }
  46303. return r;
  46304. }
  46305. function arraysEqual( a, b ) {
  46306. if ( a.length !== b.length ) return false;
  46307. for ( let i = 0, l = a.length; i < l; i ++ ) {
  46308. if ( a[ i ] !== b[ i ] ) return false;
  46309. }
  46310. return true;
  46311. }
  46312. function copyArray( a, b ) {
  46313. for ( let i = 0, l = b.length; i < l; i ++ ) {
  46314. a[ i ] = b[ i ];
  46315. }
  46316. }
  46317. // Texture unit allocation
  46318. function allocTexUnits( textures, n ) {
  46319. let r = arrayCacheI32[ n ];
  46320. if ( r === undefined ) {
  46321. r = new Int32Array( n );
  46322. arrayCacheI32[ n ] = r;
  46323. }
  46324. for ( let i = 0; i !== n; ++ i ) {
  46325. r[ i ] = textures.allocateTextureUnit();
  46326. }
  46327. return r;
  46328. }
  46329. // --- Setters ---
  46330. // Note: Defining these methods externally, because they come in a bunch
  46331. // and this way their names minify.
  46332. // Single scalar
  46333. function setValueV1f( gl, v ) {
  46334. const cache = this.cache;
  46335. if ( cache[ 0 ] === v ) return;
  46336. gl.uniform1f( this.addr, v );
  46337. cache[ 0 ] = v;
  46338. }
  46339. // Single float vector (from flat array or THREE.VectorN)
  46340. function setValueV2f( gl, v ) {
  46341. const cache = this.cache;
  46342. if ( v.x !== undefined ) {
  46343. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46344. gl.uniform2f( this.addr, v.x, v.y );
  46345. cache[ 0 ] = v.x;
  46346. cache[ 1 ] = v.y;
  46347. }
  46348. } else {
  46349. if ( arraysEqual( cache, v ) ) return;
  46350. gl.uniform2fv( this.addr, v );
  46351. copyArray( cache, v );
  46352. }
  46353. }
  46354. function setValueV3f( gl, v ) {
  46355. const cache = this.cache;
  46356. if ( v.x !== undefined ) {
  46357. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46358. gl.uniform3f( this.addr, v.x, v.y, v.z );
  46359. cache[ 0 ] = v.x;
  46360. cache[ 1 ] = v.y;
  46361. cache[ 2 ] = v.z;
  46362. }
  46363. } else if ( v.r !== undefined ) {
  46364. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  46365. gl.uniform3f( this.addr, v.r, v.g, v.b );
  46366. cache[ 0 ] = v.r;
  46367. cache[ 1 ] = v.g;
  46368. cache[ 2 ] = v.b;
  46369. }
  46370. } else {
  46371. if ( arraysEqual( cache, v ) ) return;
  46372. gl.uniform3fv( this.addr, v );
  46373. copyArray( cache, v );
  46374. }
  46375. }
  46376. function setValueV4f( gl, v ) {
  46377. const cache = this.cache;
  46378. if ( v.x !== undefined ) {
  46379. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46380. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  46381. cache[ 0 ] = v.x;
  46382. cache[ 1 ] = v.y;
  46383. cache[ 2 ] = v.z;
  46384. cache[ 3 ] = v.w;
  46385. }
  46386. } else {
  46387. if ( arraysEqual( cache, v ) ) return;
  46388. gl.uniform4fv( this.addr, v );
  46389. copyArray( cache, v );
  46390. }
  46391. }
  46392. // Single matrix (from flat array or THREE.MatrixN)
  46393. function setValueM2( gl, v ) {
  46394. const cache = this.cache;
  46395. const elements = v.elements;
  46396. if ( elements === undefined ) {
  46397. if ( arraysEqual( cache, v ) ) return;
  46398. gl.uniformMatrix2fv( this.addr, false, v );
  46399. copyArray( cache, v );
  46400. } else {
  46401. if ( arraysEqual( cache, elements ) ) return;
  46402. mat2array.set( elements );
  46403. gl.uniformMatrix2fv( this.addr, false, mat2array );
  46404. copyArray( cache, elements );
  46405. }
  46406. }
  46407. function setValueM3( gl, v ) {
  46408. const cache = this.cache;
  46409. const elements = v.elements;
  46410. if ( elements === undefined ) {
  46411. if ( arraysEqual( cache, v ) ) return;
  46412. gl.uniformMatrix3fv( this.addr, false, v );
  46413. copyArray( cache, v );
  46414. } else {
  46415. if ( arraysEqual( cache, elements ) ) return;
  46416. mat3array.set( elements );
  46417. gl.uniformMatrix3fv( this.addr, false, mat3array );
  46418. copyArray( cache, elements );
  46419. }
  46420. }
  46421. function setValueM4( gl, v ) {
  46422. const cache = this.cache;
  46423. const elements = v.elements;
  46424. if ( elements === undefined ) {
  46425. if ( arraysEqual( cache, v ) ) return;
  46426. gl.uniformMatrix4fv( this.addr, false, v );
  46427. copyArray( cache, v );
  46428. } else {
  46429. if ( arraysEqual( cache, elements ) ) return;
  46430. mat4array.set( elements );
  46431. gl.uniformMatrix4fv( this.addr, false, mat4array );
  46432. copyArray( cache, elements );
  46433. }
  46434. }
  46435. // Single integer / boolean
  46436. function setValueV1i( gl, v ) {
  46437. const cache = this.cache;
  46438. if ( cache[ 0 ] === v ) return;
  46439. gl.uniform1i( this.addr, v );
  46440. cache[ 0 ] = v;
  46441. }
  46442. // Single integer / boolean vector (from flat array or THREE.VectorN)
  46443. function setValueV2i( gl, v ) {
  46444. const cache = this.cache;
  46445. if ( v.x !== undefined ) {
  46446. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46447. gl.uniform2i( this.addr, v.x, v.y );
  46448. cache[ 0 ] = v.x;
  46449. cache[ 1 ] = v.y;
  46450. }
  46451. } else {
  46452. if ( arraysEqual( cache, v ) ) return;
  46453. gl.uniform2iv( this.addr, v );
  46454. copyArray( cache, v );
  46455. }
  46456. }
  46457. function setValueV3i( gl, v ) {
  46458. const cache = this.cache;
  46459. if ( v.x !== undefined ) {
  46460. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46461. gl.uniform3i( this.addr, v.x, v.y, v.z );
  46462. cache[ 0 ] = v.x;
  46463. cache[ 1 ] = v.y;
  46464. cache[ 2 ] = v.z;
  46465. }
  46466. } else {
  46467. if ( arraysEqual( cache, v ) ) return;
  46468. gl.uniform3iv( this.addr, v );
  46469. copyArray( cache, v );
  46470. }
  46471. }
  46472. function setValueV4i( gl, v ) {
  46473. const cache = this.cache;
  46474. if ( v.x !== undefined ) {
  46475. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46476. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  46477. cache[ 0 ] = v.x;
  46478. cache[ 1 ] = v.y;
  46479. cache[ 2 ] = v.z;
  46480. cache[ 3 ] = v.w;
  46481. }
  46482. } else {
  46483. if ( arraysEqual( cache, v ) ) return;
  46484. gl.uniform4iv( this.addr, v );
  46485. copyArray( cache, v );
  46486. }
  46487. }
  46488. // Single unsigned integer
  46489. function setValueV1ui( gl, v ) {
  46490. const cache = this.cache;
  46491. if ( cache[ 0 ] === v ) return;
  46492. gl.uniform1ui( this.addr, v );
  46493. cache[ 0 ] = v;
  46494. }
  46495. // Single unsigned integer vector (from flat array or THREE.VectorN)
  46496. function setValueV2ui( gl, v ) {
  46497. const cache = this.cache;
  46498. if ( v.x !== undefined ) {
  46499. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46500. gl.uniform2ui( this.addr, v.x, v.y );
  46501. cache[ 0 ] = v.x;
  46502. cache[ 1 ] = v.y;
  46503. }
  46504. } else {
  46505. if ( arraysEqual( cache, v ) ) return;
  46506. gl.uniform2uiv( this.addr, v );
  46507. copyArray( cache, v );
  46508. }
  46509. }
  46510. function setValueV3ui( gl, v ) {
  46511. const cache = this.cache;
  46512. if ( v.x !== undefined ) {
  46513. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46514. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  46515. cache[ 0 ] = v.x;
  46516. cache[ 1 ] = v.y;
  46517. cache[ 2 ] = v.z;
  46518. }
  46519. } else {
  46520. if ( arraysEqual( cache, v ) ) return;
  46521. gl.uniform3uiv( this.addr, v );
  46522. copyArray( cache, v );
  46523. }
  46524. }
  46525. function setValueV4ui( gl, v ) {
  46526. const cache = this.cache;
  46527. if ( v.x !== undefined ) {
  46528. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46529. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  46530. cache[ 0 ] = v.x;
  46531. cache[ 1 ] = v.y;
  46532. cache[ 2 ] = v.z;
  46533. cache[ 3 ] = v.w;
  46534. }
  46535. } else {
  46536. if ( arraysEqual( cache, v ) ) return;
  46537. gl.uniform4uiv( this.addr, v );
  46538. copyArray( cache, v );
  46539. }
  46540. }
  46541. // Single texture (2D / Cube)
  46542. function setValueT1( gl, v, textures ) {
  46543. const cache = this.cache;
  46544. const unit = textures.allocateTextureUnit();
  46545. if ( cache[ 0 ] !== unit ) {
  46546. gl.uniform1i( this.addr, unit );
  46547. cache[ 0 ] = unit;
  46548. }
  46549. let emptyTexture2D;
  46550. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46551. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  46552. emptyTexture2D = emptyShadowTexture;
  46553. } else {
  46554. emptyTexture2D = emptyTexture;
  46555. }
  46556. textures.setTexture2D( v || emptyTexture2D, unit );
  46557. }
  46558. function setValueT3D1( gl, v, textures ) {
  46559. const cache = this.cache;
  46560. const unit = textures.allocateTextureUnit();
  46561. if ( cache[ 0 ] !== unit ) {
  46562. gl.uniform1i( this.addr, unit );
  46563. cache[ 0 ] = unit;
  46564. }
  46565. textures.setTexture3D( v || empty3dTexture, unit );
  46566. }
  46567. function setValueT6( gl, v, textures ) {
  46568. const cache = this.cache;
  46569. const unit = textures.allocateTextureUnit();
  46570. if ( cache[ 0 ] !== unit ) {
  46571. gl.uniform1i( this.addr, unit );
  46572. cache[ 0 ] = unit;
  46573. }
  46574. textures.setTextureCube( v || emptyCubeTexture, unit );
  46575. }
  46576. function setValueT2DArray1( gl, v, textures ) {
  46577. const cache = this.cache;
  46578. const unit = textures.allocateTextureUnit();
  46579. if ( cache[ 0 ] !== unit ) {
  46580. gl.uniform1i( this.addr, unit );
  46581. cache[ 0 ] = unit;
  46582. }
  46583. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46584. }
  46585. // Helper to pick the right setter for the singular case
  46586. function getSingularSetter( type ) {
  46587. switch ( type ) {
  46588. case 0x1406: return setValueV1f; // FLOAT
  46589. case 0x8b50: return setValueV2f; // _VEC2
  46590. case 0x8b51: return setValueV3f; // _VEC3
  46591. case 0x8b52: return setValueV4f; // _VEC4
  46592. case 0x8b5a: return setValueM2; // _MAT2
  46593. case 0x8b5b: return setValueM3; // _MAT3
  46594. case 0x8b5c: return setValueM4; // _MAT4
  46595. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46596. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46597. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46598. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46599. case 0x1405: return setValueV1ui; // UINT
  46600. case 0x8dc6: return setValueV2ui; // _VEC2
  46601. case 0x8dc7: return setValueV3ui; // _VEC3
  46602. case 0x8dc8: return setValueV4ui; // _VEC4
  46603. case 0x8b5e: // SAMPLER_2D
  46604. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46605. case 0x8dca: // INT_SAMPLER_2D
  46606. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46607. case 0x8b62: // SAMPLER_2D_SHADOW
  46608. return setValueT1;
  46609. case 0x8b5f: // SAMPLER_3D
  46610. case 0x8dcb: // INT_SAMPLER_3D
  46611. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46612. return setValueT3D1;
  46613. case 0x8b60: // SAMPLER_CUBE
  46614. case 0x8dcc: // INT_SAMPLER_CUBE
  46615. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46616. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46617. return setValueT6;
  46618. case 0x8dc1: // SAMPLER_2D_ARRAY
  46619. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46620. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46621. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46622. return setValueT2DArray1;
  46623. }
  46624. }
  46625. // Array of scalars
  46626. function setValueV1fArray( gl, v ) {
  46627. gl.uniform1fv( this.addr, v );
  46628. }
  46629. // Array of vectors (from flat array or array of THREE.VectorN)
  46630. function setValueV2fArray( gl, v ) {
  46631. const data = flatten( v, this.size, 2 );
  46632. gl.uniform2fv( this.addr, data );
  46633. }
  46634. function setValueV3fArray( gl, v ) {
  46635. const data = flatten( v, this.size, 3 );
  46636. gl.uniform3fv( this.addr, data );
  46637. }
  46638. function setValueV4fArray( gl, v ) {
  46639. const data = flatten( v, this.size, 4 );
  46640. gl.uniform4fv( this.addr, data );
  46641. }
  46642. // Array of matrices (from flat array or array of THREE.MatrixN)
  46643. function setValueM2Array( gl, v ) {
  46644. const data = flatten( v, this.size, 4 );
  46645. gl.uniformMatrix2fv( this.addr, false, data );
  46646. }
  46647. function setValueM3Array( gl, v ) {
  46648. const data = flatten( v, this.size, 9 );
  46649. gl.uniformMatrix3fv( this.addr, false, data );
  46650. }
  46651. function setValueM4Array( gl, v ) {
  46652. const data = flatten( v, this.size, 16 );
  46653. gl.uniformMatrix4fv( this.addr, false, data );
  46654. }
  46655. // Array of integer / boolean
  46656. function setValueV1iArray( gl, v ) {
  46657. gl.uniform1iv( this.addr, v );
  46658. }
  46659. // Array of integer / boolean vectors (from flat array)
  46660. function setValueV2iArray( gl, v ) {
  46661. gl.uniform2iv( this.addr, v );
  46662. }
  46663. function setValueV3iArray( gl, v ) {
  46664. gl.uniform3iv( this.addr, v );
  46665. }
  46666. function setValueV4iArray( gl, v ) {
  46667. gl.uniform4iv( this.addr, v );
  46668. }
  46669. // Array of unsigned integer
  46670. function setValueV1uiArray( gl, v ) {
  46671. gl.uniform1uiv( this.addr, v );
  46672. }
  46673. // Array of unsigned integer vectors (from flat array)
  46674. function setValueV2uiArray( gl, v ) {
  46675. gl.uniform2uiv( this.addr, v );
  46676. }
  46677. function setValueV3uiArray( gl, v ) {
  46678. gl.uniform3uiv( this.addr, v );
  46679. }
  46680. function setValueV4uiArray( gl, v ) {
  46681. gl.uniform4uiv( this.addr, v );
  46682. }
  46683. // Array of textures (2D / 3D / Cube / 2DArray)
  46684. function setValueT1Array( gl, v, textures ) {
  46685. const cache = this.cache;
  46686. const n = v.length;
  46687. const units = allocTexUnits( textures, n );
  46688. if ( ! arraysEqual( cache, units ) ) {
  46689. gl.uniform1iv( this.addr, units );
  46690. copyArray( cache, units );
  46691. }
  46692. let emptyTexture2D;
  46693. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46694. emptyTexture2D = emptyShadowTexture;
  46695. } else {
  46696. emptyTexture2D = emptyTexture;
  46697. }
  46698. for ( let i = 0; i !== n; ++ i ) {
  46699. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46700. }
  46701. }
  46702. function setValueT3DArray( gl, v, textures ) {
  46703. const cache = this.cache;
  46704. const n = v.length;
  46705. const units = allocTexUnits( textures, n );
  46706. if ( ! arraysEqual( cache, units ) ) {
  46707. gl.uniform1iv( this.addr, units );
  46708. copyArray( cache, units );
  46709. }
  46710. for ( let i = 0; i !== n; ++ i ) {
  46711. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46712. }
  46713. }
  46714. function setValueT6Array( gl, v, textures ) {
  46715. const cache = this.cache;
  46716. const n = v.length;
  46717. const units = allocTexUnits( textures, n );
  46718. if ( ! arraysEqual( cache, units ) ) {
  46719. gl.uniform1iv( this.addr, units );
  46720. copyArray( cache, units );
  46721. }
  46722. for ( let i = 0; i !== n; ++ i ) {
  46723. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46724. }
  46725. }
  46726. function setValueT2DArrayArray( gl, v, textures ) {
  46727. const cache = this.cache;
  46728. const n = v.length;
  46729. const units = allocTexUnits( textures, n );
  46730. if ( ! arraysEqual( cache, units ) ) {
  46731. gl.uniform1iv( this.addr, units );
  46732. copyArray( cache, units );
  46733. }
  46734. for ( let i = 0; i !== n; ++ i ) {
  46735. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46736. }
  46737. }
  46738. // Helper to pick the right setter for a pure (bottom-level) array
  46739. function getPureArraySetter( type ) {
  46740. switch ( type ) {
  46741. case 0x1406: return setValueV1fArray; // FLOAT
  46742. case 0x8b50: return setValueV2fArray; // _VEC2
  46743. case 0x8b51: return setValueV3fArray; // _VEC3
  46744. case 0x8b52: return setValueV4fArray; // _VEC4
  46745. case 0x8b5a: return setValueM2Array; // _MAT2
  46746. case 0x8b5b: return setValueM3Array; // _MAT3
  46747. case 0x8b5c: return setValueM4Array; // _MAT4
  46748. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46749. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46750. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46751. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46752. case 0x1405: return setValueV1uiArray; // UINT
  46753. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46754. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46755. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46756. case 0x8b5e: // SAMPLER_2D
  46757. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46758. case 0x8dca: // INT_SAMPLER_2D
  46759. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46760. case 0x8b62: // SAMPLER_2D_SHADOW
  46761. return setValueT1Array;
  46762. case 0x8b5f: // SAMPLER_3D
  46763. case 0x8dcb: // INT_SAMPLER_3D
  46764. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46765. return setValueT3DArray;
  46766. case 0x8b60: // SAMPLER_CUBE
  46767. case 0x8dcc: // INT_SAMPLER_CUBE
  46768. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46769. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46770. return setValueT6Array;
  46771. case 0x8dc1: // SAMPLER_2D_ARRAY
  46772. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46773. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46774. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46775. return setValueT2DArrayArray;
  46776. }
  46777. }
  46778. // --- Uniform Classes ---
  46779. class SingleUniform {
  46780. constructor( id, activeInfo, addr ) {
  46781. this.id = id;
  46782. this.addr = addr;
  46783. this.cache = [];
  46784. this.type = activeInfo.type;
  46785. this.setValue = getSingularSetter( activeInfo.type );
  46786. // this.path = activeInfo.name; // DEBUG
  46787. }
  46788. }
  46789. class PureArrayUniform {
  46790. constructor( id, activeInfo, addr ) {
  46791. this.id = id;
  46792. this.addr = addr;
  46793. this.cache = [];
  46794. this.type = activeInfo.type;
  46795. this.size = activeInfo.size;
  46796. this.setValue = getPureArraySetter( activeInfo.type );
  46797. // this.path = activeInfo.name; // DEBUG
  46798. }
  46799. }
  46800. class StructuredUniform {
  46801. constructor( id ) {
  46802. this.id = id;
  46803. this.seq = [];
  46804. this.map = {};
  46805. }
  46806. setValue( gl, value, textures ) {
  46807. const seq = this.seq;
  46808. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46809. const u = seq[ i ];
  46810. u.setValue( gl, value[ u.id ], textures );
  46811. }
  46812. }
  46813. }
  46814. // --- Top-level ---
  46815. // Parser - builds up the property tree from the path strings
  46816. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46817. // extracts
  46818. // - the identifier (member name or array index)
  46819. // - followed by an optional right bracket (found when array index)
  46820. // - followed by an optional left bracket or dot (type of subscript)
  46821. //
  46822. // Note: These portions can be read in a non-overlapping fashion and
  46823. // allow straightforward parsing of the hierarchy that WebGL encodes
  46824. // in the uniform names.
  46825. function addUniform( container, uniformObject ) {
  46826. container.seq.push( uniformObject );
  46827. container.map[ uniformObject.id ] = uniformObject;
  46828. }
  46829. function parseUniform( activeInfo, addr, container ) {
  46830. const path = activeInfo.name,
  46831. pathLength = path.length;
  46832. // reset RegExp object, because of the early exit of a previous run
  46833. RePathPart.lastIndex = 0;
  46834. while ( true ) {
  46835. const match = RePathPart.exec( path ),
  46836. matchEnd = RePathPart.lastIndex;
  46837. let id = match[ 1 ];
  46838. const idIsIndex = match[ 2 ] === ']',
  46839. subscript = match[ 3 ];
  46840. if ( idIsIndex ) id = id | 0; // convert to integer
  46841. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46842. // bare name or "pure" bottom-level array "[0]" suffix
  46843. addUniform( container, subscript === undefined ?
  46844. new SingleUniform( id, activeInfo, addr ) :
  46845. new PureArrayUniform( id, activeInfo, addr ) );
  46846. break;
  46847. } else {
  46848. // step into inner node / create it in case it doesn't exist
  46849. const map = container.map;
  46850. let next = map[ id ];
  46851. if ( next === undefined ) {
  46852. next = new StructuredUniform( id );
  46853. addUniform( container, next );
  46854. }
  46855. container = next;
  46856. }
  46857. }
  46858. }
  46859. // Root Container
  46860. class WebGLUniforms {
  46861. constructor( gl, program ) {
  46862. this.seq = [];
  46863. this.map = {};
  46864. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46865. for ( let i = 0; i < n; ++ i ) {
  46866. const info = gl.getActiveUniform( program, i ),
  46867. addr = gl.getUniformLocation( program, info.name );
  46868. parseUniform( info, addr, this );
  46869. }
  46870. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46871. const shadowSamplers = [];
  46872. const otherUniforms = [];
  46873. for ( const u of this.seq ) {
  46874. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46875. shadowSamplers.push( u );
  46876. } else {
  46877. otherUniforms.push( u );
  46878. }
  46879. }
  46880. if ( shadowSamplers.length > 0 ) {
  46881. this.seq = shadowSamplers.concat( otherUniforms );
  46882. }
  46883. }
  46884. setValue( gl, name, value, textures ) {
  46885. const u = this.map[ name ];
  46886. if ( u !== undefined ) u.setValue( gl, value, textures );
  46887. }
  46888. setOptional( gl, object, name ) {
  46889. const v = object[ name ];
  46890. if ( v !== undefined ) this.setValue( gl, name, v );
  46891. }
  46892. static upload( gl, seq, values, textures ) {
  46893. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46894. const u = seq[ i ],
  46895. v = values[ u.id ];
  46896. if ( v.needsUpdate !== false ) {
  46897. // note: always updating when .needsUpdate is undefined
  46898. u.setValue( gl, v.value, textures );
  46899. }
  46900. }
  46901. }
  46902. static seqWithValue( seq, values ) {
  46903. const r = [];
  46904. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46905. const u = seq[ i ];
  46906. if ( u.id in values ) r.push( u );
  46907. }
  46908. return r;
  46909. }
  46910. }
  46911. function WebGLShader( gl, type, string ) {
  46912. const shader = gl.createShader( type );
  46913. gl.shaderSource( shader, string );
  46914. gl.compileShader( shader );
  46915. return shader;
  46916. }
  46917. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46918. const COMPLETION_STATUS_KHR = 0x91B1;
  46919. let programIdCount = 0;
  46920. function handleSource( string, errorLine ) {
  46921. const lines = string.split( '\n' );
  46922. const lines2 = [];
  46923. const from = Math.max( errorLine - 6, 0 );
  46924. const to = Math.min( errorLine + 6, lines.length );
  46925. for ( let i = from; i < to; i ++ ) {
  46926. const line = i + 1;
  46927. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46928. }
  46929. return lines2.join( '\n' );
  46930. }
  46931. const _m0 = /*@__PURE__*/ new Matrix3();
  46932. function getEncodingComponents( colorSpace ) {
  46933. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46934. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46935. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46936. case LinearTransfer:
  46937. return [ encodingMatrix, 'LinearTransferOETF' ];
  46938. case SRGBTransfer:
  46939. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46940. default:
  46941. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46942. return [ encodingMatrix, 'LinearTransferOETF' ];
  46943. }
  46944. }
  46945. function getShaderErrors( gl, shader, type ) {
  46946. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46947. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46948. const errors = shaderInfoLog.trim();
  46949. if ( status && errors === '' ) return '';
  46950. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46951. if ( errorMatches ) {
  46952. // --enable-privileged-webgl-extension
  46953. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46954. const errorLine = parseInt( errorMatches[ 1 ] );
  46955. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46956. } else {
  46957. return errors;
  46958. }
  46959. }
  46960. function getTexelEncodingFunction( functionName, colorSpace ) {
  46961. const components = getEncodingComponents( colorSpace );
  46962. return [
  46963. `vec4 ${functionName}( vec4 value ) {`,
  46964. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46965. '}',
  46966. ].join( '\n' );
  46967. }
  46968. const toneMappingFunctions = {
  46969. [ LinearToneMapping ]: 'Linear',
  46970. [ ReinhardToneMapping ]: 'Reinhard',
  46971. [ CineonToneMapping ]: 'Cineon',
  46972. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  46973. [ AgXToneMapping ]: 'AgX',
  46974. [ NeutralToneMapping ]: 'Neutral',
  46975. [ CustomToneMapping ]: 'Custom'
  46976. };
  46977. function getToneMappingFunction( functionName, toneMapping ) {
  46978. const toneMappingName = toneMappingFunctions[ toneMapping ];
  46979. if ( toneMappingName === undefined ) {
  46980. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46981. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  46982. }
  46983. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46984. }
  46985. const _v0 = /*@__PURE__*/ new Vector3();
  46986. function getLuminanceFunction() {
  46987. ColorManagement.getLuminanceCoefficients( _v0 );
  46988. const r = _v0.x.toFixed( 4 );
  46989. const g = _v0.y.toFixed( 4 );
  46990. const b = _v0.z.toFixed( 4 );
  46991. return [
  46992. 'float luminance( const in vec3 rgb ) {',
  46993. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46994. ' return dot( weights, rgb );',
  46995. '}'
  46996. ].join( '\n' );
  46997. }
  46998. function generateVertexExtensions( parameters ) {
  46999. const chunks = [
  47000. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  47001. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  47002. ];
  47003. return chunks.filter( filterEmptyLine ).join( '\n' );
  47004. }
  47005. function generateDefines( defines ) {
  47006. const chunks = [];
  47007. for ( const name in defines ) {
  47008. const value = defines[ name ];
  47009. if ( value === false ) continue;
  47010. chunks.push( '#define ' + name + ' ' + value );
  47011. }
  47012. return chunks.join( '\n' );
  47013. }
  47014. function fetchAttributeLocations( gl, program ) {
  47015. const attributes = {};
  47016. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  47017. for ( let i = 0; i < n; i ++ ) {
  47018. const info = gl.getActiveAttrib( program, i );
  47019. const name = info.name;
  47020. let locationSize = 1;
  47021. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  47022. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  47023. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  47024. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  47025. attributes[ name ] = {
  47026. type: info.type,
  47027. location: gl.getAttribLocation( program, name ),
  47028. locationSize: locationSize
  47029. };
  47030. }
  47031. return attributes;
  47032. }
  47033. function filterEmptyLine( string ) {
  47034. return string !== '';
  47035. }
  47036. function replaceLightNums( string, parameters ) {
  47037. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  47038. return string
  47039. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  47040. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  47041. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  47042. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  47043. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  47044. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  47045. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  47046. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  47047. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  47048. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  47049. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  47050. }
  47051. function replaceClippingPlaneNums( string, parameters ) {
  47052. return string
  47053. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  47054. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  47055. }
  47056. // Resolve Includes
  47057. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  47058. function resolveIncludes( string ) {
  47059. return string.replace( includePattern, includeReplacer );
  47060. }
  47061. const shaderChunkMap = new Map();
  47062. function includeReplacer( match, include ) {
  47063. let string = ShaderChunk[ include ];
  47064. if ( string === undefined ) {
  47065. const newInclude = shaderChunkMap.get( include );
  47066. if ( newInclude !== undefined ) {
  47067. string = ShaderChunk[ newInclude ];
  47068. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  47069. } else {
  47070. throw new Error( 'Can not resolve #include <' + include + '>' );
  47071. }
  47072. }
  47073. return resolveIncludes( string );
  47074. }
  47075. // Unroll Loops
  47076. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  47077. function unrollLoops( string ) {
  47078. return string.replace( unrollLoopPattern, loopReplacer );
  47079. }
  47080. function loopReplacer( match, start, end, snippet ) {
  47081. let string = '';
  47082. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  47083. string += snippet
  47084. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  47085. .replace( /UNROLLED_LOOP_INDEX/g, i );
  47086. }
  47087. return string;
  47088. }
  47089. //
  47090. function generatePrecision( parameters ) {
  47091. let precisionstring = `precision ${parameters.precision} float;
  47092. precision ${parameters.precision} int;
  47093. precision ${parameters.precision} sampler2D;
  47094. precision ${parameters.precision} samplerCube;
  47095. precision ${parameters.precision} sampler3D;
  47096. precision ${parameters.precision} sampler2DArray;
  47097. precision ${parameters.precision} sampler2DShadow;
  47098. precision ${parameters.precision} samplerCubeShadow;
  47099. precision ${parameters.precision} sampler2DArrayShadow;
  47100. precision ${parameters.precision} isampler2D;
  47101. precision ${parameters.precision} isampler3D;
  47102. precision ${parameters.precision} isamplerCube;
  47103. precision ${parameters.precision} isampler2DArray;
  47104. precision ${parameters.precision} usampler2D;
  47105. precision ${parameters.precision} usampler3D;
  47106. precision ${parameters.precision} usamplerCube;
  47107. precision ${parameters.precision} usampler2DArray;
  47108. `;
  47109. if ( parameters.precision === 'highp' ) {
  47110. precisionstring += '\n#define HIGH_PRECISION';
  47111. } else if ( parameters.precision === 'mediump' ) {
  47112. precisionstring += '\n#define MEDIUM_PRECISION';
  47113. } else if ( parameters.precision === 'lowp' ) {
  47114. precisionstring += '\n#define LOW_PRECISION';
  47115. }
  47116. return precisionstring;
  47117. }
  47118. const shadowMapTypeDefines = {
  47119. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  47120. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  47121. };
  47122. function generateShadowMapTypeDefine( parameters ) {
  47123. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  47124. }
  47125. const envMapTypeDefines = {
  47126. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  47127. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  47128. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  47129. };
  47130. function generateEnvMapTypeDefine( parameters ) {
  47131. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  47132. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  47133. }
  47134. const envMapModeDefines = {
  47135. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  47136. };
  47137. function generateEnvMapModeDefine( parameters ) {
  47138. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  47139. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  47140. }
  47141. const envMapBlendingDefines = {
  47142. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  47143. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  47144. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  47145. };
  47146. function generateEnvMapBlendingDefine( parameters ) {
  47147. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  47148. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  47149. }
  47150. function generateCubeUVSize( parameters ) {
  47151. const imageHeight = parameters.envMapCubeUVHeight;
  47152. if ( imageHeight === null ) return null;
  47153. const maxMip = Math.log2( imageHeight ) - 2;
  47154. const texelHeight = 1.0 / imageHeight;
  47155. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  47156. return { texelWidth, texelHeight, maxMip };
  47157. }
  47158. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  47159. // TODO Send this event to Three.js DevTools
  47160. // log( 'WebGLProgram', cacheKey );
  47161. const gl = renderer.getContext();
  47162. const defines = parameters.defines;
  47163. let vertexShader = parameters.vertexShader;
  47164. let fragmentShader = parameters.fragmentShader;
  47165. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  47166. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  47167. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  47168. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  47169. const envMapCubeUVSize = generateCubeUVSize( parameters );
  47170. const customVertexExtensions = generateVertexExtensions( parameters );
  47171. const customDefines = generateDefines( defines );
  47172. const program = gl.createProgram();
  47173. let prefixVertex, prefixFragment;
  47174. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  47175. if ( parameters.isRawShaderMaterial ) {
  47176. prefixVertex = [
  47177. '#define SHADER_TYPE ' + parameters.shaderType,
  47178. '#define SHADER_NAME ' + parameters.shaderName,
  47179. customDefines
  47180. ].filter( filterEmptyLine ).join( '\n' );
  47181. if ( prefixVertex.length > 0 ) {
  47182. prefixVertex += '\n';
  47183. }
  47184. prefixFragment = [
  47185. '#define SHADER_TYPE ' + parameters.shaderType,
  47186. '#define SHADER_NAME ' + parameters.shaderName,
  47187. customDefines
  47188. ].filter( filterEmptyLine ).join( '\n' );
  47189. if ( prefixFragment.length > 0 ) {
  47190. prefixFragment += '\n';
  47191. }
  47192. } else {
  47193. prefixVertex = [
  47194. generatePrecision( parameters ),
  47195. '#define SHADER_TYPE ' + parameters.shaderType,
  47196. '#define SHADER_NAME ' + parameters.shaderName,
  47197. customDefines,
  47198. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  47199. parameters.batching ? '#define USE_BATCHING' : '',
  47200. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  47201. parameters.instancing ? '#define USE_INSTANCING' : '',
  47202. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  47203. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  47204. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47205. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47206. parameters.map ? '#define USE_MAP' : '',
  47207. parameters.envMap ? '#define USE_ENVMAP' : '',
  47208. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47209. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47210. parameters.aoMap ? '#define USE_AOMAP' : '',
  47211. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47212. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47213. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47214. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47215. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  47216. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47217. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47218. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47219. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47220. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47221. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47222. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47223. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47224. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47225. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47226. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47227. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47228. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47229. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47230. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47231. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47232. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47233. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47234. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47235. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47236. //
  47237. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  47238. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  47239. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  47240. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  47241. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  47242. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  47243. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  47244. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  47245. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  47246. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  47247. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  47248. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  47249. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  47250. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  47251. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  47252. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  47253. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  47254. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  47255. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  47256. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  47257. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  47258. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  47259. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  47260. //
  47261. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47262. parameters.vertexColors ? '#define USE_COLOR' : '',
  47263. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  47264. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47265. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47266. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47267. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47268. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47269. parameters.skinning ? '#define USE_SKINNING' : '',
  47270. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  47271. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  47272. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  47273. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  47274. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  47275. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47276. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47277. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47278. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47279. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  47280. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47281. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47282. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47283. 'uniform mat4 modelMatrix;',
  47284. 'uniform mat4 modelViewMatrix;',
  47285. 'uniform mat4 projectionMatrix;',
  47286. 'uniform mat4 viewMatrix;',
  47287. 'uniform mat3 normalMatrix;',
  47288. 'uniform vec3 cameraPosition;',
  47289. 'uniform bool isOrthographic;',
  47290. '#ifdef USE_INSTANCING',
  47291. ' attribute mat4 instanceMatrix;',
  47292. '#endif',
  47293. '#ifdef USE_INSTANCING_COLOR',
  47294. ' attribute vec3 instanceColor;',
  47295. '#endif',
  47296. '#ifdef USE_INSTANCING_MORPH',
  47297. ' uniform sampler2D morphTexture;',
  47298. '#endif',
  47299. 'attribute vec3 position;',
  47300. 'attribute vec3 normal;',
  47301. 'attribute vec2 uv;',
  47302. '#ifdef USE_UV1',
  47303. ' attribute vec2 uv1;',
  47304. '#endif',
  47305. '#ifdef USE_UV2',
  47306. ' attribute vec2 uv2;',
  47307. '#endif',
  47308. '#ifdef USE_UV3',
  47309. ' attribute vec2 uv3;',
  47310. '#endif',
  47311. '#ifdef USE_TANGENT',
  47312. ' attribute vec4 tangent;',
  47313. '#endif',
  47314. '#if defined( USE_COLOR_ALPHA )',
  47315. ' attribute vec4 color;',
  47316. '#elif defined( USE_COLOR )',
  47317. ' attribute vec3 color;',
  47318. '#endif',
  47319. '#ifdef USE_SKINNING',
  47320. ' attribute vec4 skinIndex;',
  47321. ' attribute vec4 skinWeight;',
  47322. '#endif',
  47323. '\n'
  47324. ].filter( filterEmptyLine ).join( '\n' );
  47325. prefixFragment = [
  47326. generatePrecision( parameters ),
  47327. '#define SHADER_TYPE ' + parameters.shaderType,
  47328. '#define SHADER_NAME ' + parameters.shaderName,
  47329. customDefines,
  47330. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47331. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47332. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  47333. parameters.map ? '#define USE_MAP' : '',
  47334. parameters.matcap ? '#define USE_MATCAP' : '',
  47335. parameters.envMap ? '#define USE_ENVMAP' : '',
  47336. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  47337. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47338. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  47339. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  47340. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  47341. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  47342. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47343. parameters.aoMap ? '#define USE_AOMAP' : '',
  47344. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47345. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47346. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47347. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47348. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47349. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47350. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47351. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  47352. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47353. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47354. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47355. parameters.dispersion ? '#define USE_DISPERSION' : '',
  47356. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  47357. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47358. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47359. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47360. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47361. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47362. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47363. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47364. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47365. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  47366. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47367. parameters.sheen ? '#define USE_SHEEN' : '',
  47368. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47369. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47370. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47371. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47372. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47373. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47374. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  47375. parameters.vertexAlphas || parameters.batchingColor ? '#define USE_COLOR_ALPHA' : '',
  47376. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47377. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47378. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47379. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47380. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  47381. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47382. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47383. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47384. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47385. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47386. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  47387. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47388. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  47389. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  47390. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47391. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47392. 'uniform mat4 viewMatrix;',
  47393. 'uniform vec3 cameraPosition;',
  47394. 'uniform bool isOrthographic;',
  47395. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  47396. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  47397. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  47398. parameters.dithering ? '#define DITHERING' : '',
  47399. parameters.opaque ? '#define OPAQUE' : '',
  47400. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  47401. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  47402. getLuminanceFunction(),
  47403. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  47404. '\n'
  47405. ].filter( filterEmptyLine ).join( '\n' );
  47406. }
  47407. vertexShader = resolveIncludes( vertexShader );
  47408. vertexShader = replaceLightNums( vertexShader, parameters );
  47409. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  47410. fragmentShader = resolveIncludes( fragmentShader );
  47411. fragmentShader = replaceLightNums( fragmentShader, parameters );
  47412. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  47413. vertexShader = unrollLoops( vertexShader );
  47414. fragmentShader = unrollLoops( fragmentShader );
  47415. if ( parameters.isRawShaderMaterial !== true ) {
  47416. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  47417. versionString = '#version 300 es\n';
  47418. prefixVertex = [
  47419. customVertexExtensions,
  47420. '#define attribute in',
  47421. '#define varying out',
  47422. '#define texture2D texture'
  47423. ].join( '\n' ) + '\n' + prefixVertex;
  47424. prefixFragment = [
  47425. '#define varying in',
  47426. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  47427. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  47428. '#define gl_FragDepthEXT gl_FragDepth',
  47429. '#define texture2D texture',
  47430. '#define textureCube texture',
  47431. '#define texture2DProj textureProj',
  47432. '#define texture2DLodEXT textureLod',
  47433. '#define texture2DProjLodEXT textureProjLod',
  47434. '#define textureCubeLodEXT textureLod',
  47435. '#define texture2DGradEXT textureGrad',
  47436. '#define texture2DProjGradEXT textureProjGrad',
  47437. '#define textureCubeGradEXT textureGrad'
  47438. ].join( '\n' ) + '\n' + prefixFragment;
  47439. }
  47440. const vertexGlsl = versionString + prefixVertex + vertexShader;
  47441. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  47442. // log( '*VERTEX*', vertexGlsl );
  47443. // log( '*FRAGMENT*', fragmentGlsl );
  47444. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  47445. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  47446. gl.attachShader( program, glVertexShader );
  47447. gl.attachShader( program, glFragmentShader );
  47448. // Force a particular attribute to index 0.
  47449. if ( parameters.index0AttributeName !== undefined ) {
  47450. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  47451. } else if ( parameters.morphTargets === true ) {
  47452. // programs with morphTargets displace position out of attribute 0
  47453. gl.bindAttribLocation( program, 0, 'position' );
  47454. }
  47455. gl.linkProgram( program );
  47456. function onFirstUse( self ) {
  47457. // check for link errors
  47458. if ( renderer.debug.checkShaderErrors ) {
  47459. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  47460. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  47461. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  47462. const programLog = programInfoLog.trim();
  47463. const vertexLog = vertexShaderInfoLog.trim();
  47464. const fragmentLog = fragmentShaderInfoLog.trim();
  47465. let runnable = true;
  47466. let haveDiagnostics = true;
  47467. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  47468. runnable = false;
  47469. if ( typeof renderer.debug.onShaderError === 'function' ) {
  47470. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  47471. } else {
  47472. // default error reporting
  47473. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  47474. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  47475. error(
  47476. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47477. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  47478. 'Material Name: ' + self.name + '\n' +
  47479. 'Material Type: ' + self.type + '\n\n' +
  47480. 'Program Info Log: ' + programLog + '\n' +
  47481. vertexErrors + '\n' +
  47482. fragmentErrors
  47483. );
  47484. }
  47485. } else if ( programLog !== '' ) {
  47486. warn( 'WebGLProgram: Program Info Log:', programLog );
  47487. } else if ( vertexLog === '' || fragmentLog === '' ) {
  47488. haveDiagnostics = false;
  47489. }
  47490. if ( haveDiagnostics ) {
  47491. self.diagnostics = {
  47492. runnable: runnable,
  47493. programLog: programLog,
  47494. vertexShader: {
  47495. log: vertexLog,
  47496. prefix: prefixVertex
  47497. },
  47498. fragmentShader: {
  47499. log: fragmentLog,
  47500. prefix: prefixFragment
  47501. }
  47502. };
  47503. }
  47504. }
  47505. // Clean up
  47506. // Crashes in iOS9 and iOS10. #18402
  47507. // gl.detachShader( program, glVertexShader );
  47508. // gl.detachShader( program, glFragmentShader );
  47509. gl.deleteShader( glVertexShader );
  47510. gl.deleteShader( glFragmentShader );
  47511. cachedUniforms = new WebGLUniforms( gl, program );
  47512. cachedAttributes = fetchAttributeLocations( gl, program );
  47513. }
  47514. // set up caching for uniform locations
  47515. let cachedUniforms;
  47516. this.getUniforms = function () {
  47517. if ( cachedUniforms === undefined ) {
  47518. // Populates cachedUniforms and cachedAttributes
  47519. onFirstUse( this );
  47520. }
  47521. return cachedUniforms;
  47522. };
  47523. // set up caching for attribute locations
  47524. let cachedAttributes;
  47525. this.getAttributes = function () {
  47526. if ( cachedAttributes === undefined ) {
  47527. // Populates cachedAttributes and cachedUniforms
  47528. onFirstUse( this );
  47529. }
  47530. return cachedAttributes;
  47531. };
  47532. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  47533. // flag the program as ready immediately. It may cause a stall when it's first used.
  47534. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  47535. this.isReady = function () {
  47536. if ( programReady === false ) {
  47537. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  47538. }
  47539. return programReady;
  47540. };
  47541. // free resource
  47542. this.destroy = function () {
  47543. bindingStates.releaseStatesOfProgram( this );
  47544. gl.deleteProgram( program );
  47545. this.program = undefined;
  47546. };
  47547. //
  47548. this.type = parameters.shaderType;
  47549. this.name = parameters.shaderName;
  47550. this.id = programIdCount ++;
  47551. this.cacheKey = cacheKey;
  47552. this.usedTimes = 1;
  47553. this.program = program;
  47554. this.vertexShader = glVertexShader;
  47555. this.fragmentShader = glFragmentShader;
  47556. return this;
  47557. }
  47558. let _id = 0;
  47559. class WebGLShaderCache {
  47560. constructor() {
  47561. this.shaderCache = new Map();
  47562. this.materialCache = new Map();
  47563. }
  47564. update( material ) {
  47565. const vertexShader = material.vertexShader;
  47566. const fragmentShader = material.fragmentShader;
  47567. const vertexShaderStage = this._getShaderStage( vertexShader );
  47568. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47569. const materialShaders = this._getShaderCacheForMaterial( material );
  47570. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47571. materialShaders.add( vertexShaderStage );
  47572. vertexShaderStage.usedTimes ++;
  47573. }
  47574. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47575. materialShaders.add( fragmentShaderStage );
  47576. fragmentShaderStage.usedTimes ++;
  47577. }
  47578. return this;
  47579. }
  47580. remove( material ) {
  47581. const materialShaders = this.materialCache.get( material );
  47582. for ( const shaderStage of materialShaders ) {
  47583. shaderStage.usedTimes --;
  47584. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47585. }
  47586. this.materialCache.delete( material );
  47587. return this;
  47588. }
  47589. getVertexShaderID( material ) {
  47590. return this._getShaderStage( material.vertexShader ).id;
  47591. }
  47592. getFragmentShaderID( material ) {
  47593. return this._getShaderStage( material.fragmentShader ).id;
  47594. }
  47595. dispose() {
  47596. this.shaderCache.clear();
  47597. this.materialCache.clear();
  47598. }
  47599. _getShaderCacheForMaterial( material ) {
  47600. const cache = this.materialCache;
  47601. let set = cache.get( material );
  47602. if ( set === undefined ) {
  47603. set = new Set();
  47604. cache.set( material, set );
  47605. }
  47606. return set;
  47607. }
  47608. _getShaderStage( code ) {
  47609. const cache = this.shaderCache;
  47610. let stage = cache.get( code );
  47611. if ( stage === undefined ) {
  47612. stage = new WebGLShaderStage( code );
  47613. cache.set( code, stage );
  47614. }
  47615. return stage;
  47616. }
  47617. }
  47618. class WebGLShaderStage {
  47619. constructor( code ) {
  47620. this.id = _id ++;
  47621. this.code = code;
  47622. this.usedTimes = 0;
  47623. }
  47624. }
  47625. function WebGLPrograms( renderer, environments, extensions, capabilities, bindingStates, clipping ) {
  47626. const _programLayers = new Layers();
  47627. const _customShaders = new WebGLShaderCache();
  47628. const _activeChannels = new Set();
  47629. const programs = [];
  47630. const programsMap = new Map();
  47631. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47632. let precision = capabilities.precision;
  47633. const shaderIDs = {
  47634. MeshDepthMaterial: 'depth',
  47635. MeshDistanceMaterial: 'distance',
  47636. MeshNormalMaterial: 'normal',
  47637. MeshBasicMaterial: 'basic',
  47638. MeshLambertMaterial: 'lambert',
  47639. MeshPhongMaterial: 'phong',
  47640. MeshToonMaterial: 'toon',
  47641. MeshStandardMaterial: 'physical',
  47642. MeshPhysicalMaterial: 'physical',
  47643. MeshMatcapMaterial: 'matcap',
  47644. LineBasicMaterial: 'basic',
  47645. LineDashedMaterial: 'dashed',
  47646. PointsMaterial: 'points',
  47647. ShadowMaterial: 'shadow',
  47648. SpriteMaterial: 'sprite'
  47649. };
  47650. function getChannel( value ) {
  47651. _activeChannels.add( value );
  47652. if ( value === 0 ) return 'uv';
  47653. return `uv${ value }`;
  47654. }
  47655. function getParameters( material, lights, shadows, scene, object ) {
  47656. const fog = scene.fog;
  47657. const geometry = object.geometry;
  47658. const environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null;
  47659. const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap );
  47660. const envMap = environments.get( material.envMap || environment, usePMREM );
  47661. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47662. const shaderID = shaderIDs[ material.type ];
  47663. // heuristics to create shader parameters according to lights in the scene
  47664. // (not to blow over maxLights budget)
  47665. if ( material.precision !== null ) {
  47666. precision = capabilities.getMaxPrecision( material.precision );
  47667. if ( precision !== material.precision ) {
  47668. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47669. }
  47670. }
  47671. //
  47672. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47673. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47674. let morphTextureStride = 0;
  47675. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47676. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47677. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47678. //
  47679. let vertexShader, fragmentShader;
  47680. let customVertexShaderID, customFragmentShaderID;
  47681. if ( shaderID ) {
  47682. const shader = ShaderLib[ shaderID ];
  47683. vertexShader = shader.vertexShader;
  47684. fragmentShader = shader.fragmentShader;
  47685. } else {
  47686. vertexShader = material.vertexShader;
  47687. fragmentShader = material.fragmentShader;
  47688. _customShaders.update( material );
  47689. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47690. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47691. }
  47692. const currentRenderTarget = renderer.getRenderTarget();
  47693. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47694. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47695. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47696. const HAS_MAP = !! material.map;
  47697. const HAS_MATCAP = !! material.matcap;
  47698. const HAS_ENVMAP = !! envMap;
  47699. const HAS_AOMAP = !! material.aoMap;
  47700. const HAS_LIGHTMAP = !! material.lightMap;
  47701. const HAS_BUMPMAP = !! material.bumpMap;
  47702. const HAS_NORMALMAP = !! material.normalMap;
  47703. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47704. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47705. const HAS_METALNESSMAP = !! material.metalnessMap;
  47706. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47707. const HAS_ANISOTROPY = material.anisotropy > 0;
  47708. const HAS_CLEARCOAT = material.clearcoat > 0;
  47709. const HAS_DISPERSION = material.dispersion > 0;
  47710. const HAS_IRIDESCENCE = material.iridescence > 0;
  47711. const HAS_SHEEN = material.sheen > 0;
  47712. const HAS_TRANSMISSION = material.transmission > 0;
  47713. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47714. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47715. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47716. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47717. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47718. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47719. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47720. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47721. const HAS_SPECULARMAP = !! material.specularMap;
  47722. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47723. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47724. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47725. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47726. const HAS_GRADIENTMAP = !! material.gradientMap;
  47727. const HAS_ALPHAMAP = !! material.alphaMap;
  47728. const HAS_ALPHATEST = material.alphaTest > 0;
  47729. const HAS_ALPHAHASH = !! material.alphaHash;
  47730. const HAS_EXTENSIONS = !! material.extensions;
  47731. let toneMapping = NoToneMapping;
  47732. if ( material.toneMapped ) {
  47733. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47734. toneMapping = renderer.toneMapping;
  47735. }
  47736. }
  47737. const parameters = {
  47738. shaderID: shaderID,
  47739. shaderType: material.type,
  47740. shaderName: material.name,
  47741. vertexShader: vertexShader,
  47742. fragmentShader: fragmentShader,
  47743. defines: material.defines,
  47744. customVertexShaderID: customVertexShaderID,
  47745. customFragmentShaderID: customFragmentShaderID,
  47746. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47747. glslVersion: material.glslVersion,
  47748. precision: precision,
  47749. batching: IS_BATCHEDMESH,
  47750. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47751. instancing: IS_INSTANCEDMESH,
  47752. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47753. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47754. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47755. alphaToCoverage: !! material.alphaToCoverage,
  47756. map: HAS_MAP,
  47757. matcap: HAS_MATCAP,
  47758. envMap: HAS_ENVMAP,
  47759. envMapMode: HAS_ENVMAP && envMap.mapping,
  47760. envMapCubeUVHeight: envMapCubeUVHeight,
  47761. aoMap: HAS_AOMAP,
  47762. lightMap: HAS_LIGHTMAP,
  47763. bumpMap: HAS_BUMPMAP,
  47764. normalMap: HAS_NORMALMAP,
  47765. displacementMap: HAS_DISPLACEMENTMAP,
  47766. emissiveMap: HAS_EMISSIVEMAP,
  47767. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47768. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47769. metalnessMap: HAS_METALNESSMAP,
  47770. roughnessMap: HAS_ROUGHNESSMAP,
  47771. anisotropy: HAS_ANISOTROPY,
  47772. anisotropyMap: HAS_ANISOTROPYMAP,
  47773. clearcoat: HAS_CLEARCOAT,
  47774. clearcoatMap: HAS_CLEARCOATMAP,
  47775. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47776. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47777. dispersion: HAS_DISPERSION,
  47778. iridescence: HAS_IRIDESCENCE,
  47779. iridescenceMap: HAS_IRIDESCENCEMAP,
  47780. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47781. sheen: HAS_SHEEN,
  47782. sheenColorMap: HAS_SHEEN_COLORMAP,
  47783. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47784. specularMap: HAS_SPECULARMAP,
  47785. specularColorMap: HAS_SPECULAR_COLORMAP,
  47786. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47787. transmission: HAS_TRANSMISSION,
  47788. transmissionMap: HAS_TRANSMISSIONMAP,
  47789. thicknessMap: HAS_THICKNESSMAP,
  47790. gradientMap: HAS_GRADIENTMAP,
  47791. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47792. alphaMap: HAS_ALPHAMAP,
  47793. alphaTest: HAS_ALPHATEST,
  47794. alphaHash: HAS_ALPHAHASH,
  47795. combine: material.combine,
  47796. //
  47797. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47798. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47799. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47800. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47801. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47802. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47803. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47804. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47805. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47806. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47807. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47808. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47809. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47810. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47811. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47812. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47813. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47814. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47815. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47816. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47817. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47818. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47819. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47820. //
  47821. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47822. vertexColors: material.vertexColors,
  47823. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47824. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47825. fog: !! fog,
  47826. useFog: material.fog === true,
  47827. fogExp2: ( !! fog && fog.isFogExp2 ),
  47828. flatShading: material.wireframe === false && (
  47829. material.flatShading === true ||
  47830. ( geometry.attributes.normal === undefined && HAS_NORMALMAP === false &&
  47831. ( material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isMeshPhysicalMaterial )
  47832. )
  47833. ),
  47834. sizeAttenuation: material.sizeAttenuation === true,
  47835. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47836. reversedDepthBuffer: reversedDepthBuffer,
  47837. skinning: object.isSkinnedMesh === true,
  47838. morphTargets: geometry.morphAttributes.position !== undefined,
  47839. morphNormals: geometry.morphAttributes.normal !== undefined,
  47840. morphColors: geometry.morphAttributes.color !== undefined,
  47841. morphTargetsCount: morphTargetsCount,
  47842. morphTextureStride: morphTextureStride,
  47843. numDirLights: lights.directional.length,
  47844. numPointLights: lights.point.length,
  47845. numSpotLights: lights.spot.length,
  47846. numSpotLightMaps: lights.spotLightMap.length,
  47847. numRectAreaLights: lights.rectArea.length,
  47848. numHemiLights: lights.hemi.length,
  47849. numDirLightShadows: lights.directionalShadowMap.length,
  47850. numPointLightShadows: lights.pointShadowMap.length,
  47851. numSpotLightShadows: lights.spotShadowMap.length,
  47852. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47853. numLightProbes: lights.numLightProbes,
  47854. numClippingPlanes: clipping.numPlanes,
  47855. numClipIntersection: clipping.numIntersection,
  47856. dithering: material.dithering,
  47857. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47858. shadowMapType: renderer.shadowMap.type,
  47859. toneMapping: toneMapping,
  47860. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47861. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47862. premultipliedAlpha: material.premultipliedAlpha,
  47863. doubleSided: material.side === DoubleSide,
  47864. flipSided: material.side === BackSide,
  47865. useDepthPacking: material.depthPacking >= 0,
  47866. depthPacking: material.depthPacking || 0,
  47867. index0AttributeName: material.index0AttributeName,
  47868. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47869. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47870. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47871. customProgramCacheKey: material.customProgramCacheKey()
  47872. };
  47873. // the usage of getChannel() determines the active texture channels for this shader
  47874. parameters.vertexUv1s = _activeChannels.has( 1 );
  47875. parameters.vertexUv2s = _activeChannels.has( 2 );
  47876. parameters.vertexUv3s = _activeChannels.has( 3 );
  47877. _activeChannels.clear();
  47878. return parameters;
  47879. }
  47880. function getProgramCacheKey( parameters ) {
  47881. const array = [];
  47882. if ( parameters.shaderID ) {
  47883. array.push( parameters.shaderID );
  47884. } else {
  47885. array.push( parameters.customVertexShaderID );
  47886. array.push( parameters.customFragmentShaderID );
  47887. }
  47888. if ( parameters.defines !== undefined ) {
  47889. for ( const name in parameters.defines ) {
  47890. array.push( name );
  47891. array.push( parameters.defines[ name ] );
  47892. }
  47893. }
  47894. if ( parameters.isRawShaderMaterial === false ) {
  47895. getProgramCacheKeyParameters( array, parameters );
  47896. getProgramCacheKeyBooleans( array, parameters );
  47897. array.push( renderer.outputColorSpace );
  47898. }
  47899. array.push( parameters.customProgramCacheKey );
  47900. return array.join();
  47901. }
  47902. function getProgramCacheKeyParameters( array, parameters ) {
  47903. array.push( parameters.precision );
  47904. array.push( parameters.outputColorSpace );
  47905. array.push( parameters.envMapMode );
  47906. array.push( parameters.envMapCubeUVHeight );
  47907. array.push( parameters.mapUv );
  47908. array.push( parameters.alphaMapUv );
  47909. array.push( parameters.lightMapUv );
  47910. array.push( parameters.aoMapUv );
  47911. array.push( parameters.bumpMapUv );
  47912. array.push( parameters.normalMapUv );
  47913. array.push( parameters.displacementMapUv );
  47914. array.push( parameters.emissiveMapUv );
  47915. array.push( parameters.metalnessMapUv );
  47916. array.push( parameters.roughnessMapUv );
  47917. array.push( parameters.anisotropyMapUv );
  47918. array.push( parameters.clearcoatMapUv );
  47919. array.push( parameters.clearcoatNormalMapUv );
  47920. array.push( parameters.clearcoatRoughnessMapUv );
  47921. array.push( parameters.iridescenceMapUv );
  47922. array.push( parameters.iridescenceThicknessMapUv );
  47923. array.push( parameters.sheenColorMapUv );
  47924. array.push( parameters.sheenRoughnessMapUv );
  47925. array.push( parameters.specularMapUv );
  47926. array.push( parameters.specularColorMapUv );
  47927. array.push( parameters.specularIntensityMapUv );
  47928. array.push( parameters.transmissionMapUv );
  47929. array.push( parameters.thicknessMapUv );
  47930. array.push( parameters.combine );
  47931. array.push( parameters.fogExp2 );
  47932. array.push( parameters.sizeAttenuation );
  47933. array.push( parameters.morphTargetsCount );
  47934. array.push( parameters.morphAttributeCount );
  47935. array.push( parameters.numDirLights );
  47936. array.push( parameters.numPointLights );
  47937. array.push( parameters.numSpotLights );
  47938. array.push( parameters.numSpotLightMaps );
  47939. array.push( parameters.numHemiLights );
  47940. array.push( parameters.numRectAreaLights );
  47941. array.push( parameters.numDirLightShadows );
  47942. array.push( parameters.numPointLightShadows );
  47943. array.push( parameters.numSpotLightShadows );
  47944. array.push( parameters.numSpotLightShadowsWithMaps );
  47945. array.push( parameters.numLightProbes );
  47946. array.push( parameters.shadowMapType );
  47947. array.push( parameters.toneMapping );
  47948. array.push( parameters.numClippingPlanes );
  47949. array.push( parameters.numClipIntersection );
  47950. array.push( parameters.depthPacking );
  47951. }
  47952. function getProgramCacheKeyBooleans( array, parameters ) {
  47953. _programLayers.disableAll();
  47954. if ( parameters.instancing )
  47955. _programLayers.enable( 0 );
  47956. if ( parameters.instancingColor )
  47957. _programLayers.enable( 1 );
  47958. if ( parameters.instancingMorph )
  47959. _programLayers.enable( 2 );
  47960. if ( parameters.matcap )
  47961. _programLayers.enable( 3 );
  47962. if ( parameters.envMap )
  47963. _programLayers.enable( 4 );
  47964. if ( parameters.normalMapObjectSpace )
  47965. _programLayers.enable( 5 );
  47966. if ( parameters.normalMapTangentSpace )
  47967. _programLayers.enable( 6 );
  47968. if ( parameters.clearcoat )
  47969. _programLayers.enable( 7 );
  47970. if ( parameters.iridescence )
  47971. _programLayers.enable( 8 );
  47972. if ( parameters.alphaTest )
  47973. _programLayers.enable( 9 );
  47974. if ( parameters.vertexColors )
  47975. _programLayers.enable( 10 );
  47976. if ( parameters.vertexAlphas )
  47977. _programLayers.enable( 11 );
  47978. if ( parameters.vertexUv1s )
  47979. _programLayers.enable( 12 );
  47980. if ( parameters.vertexUv2s )
  47981. _programLayers.enable( 13 );
  47982. if ( parameters.vertexUv3s )
  47983. _programLayers.enable( 14 );
  47984. if ( parameters.vertexTangents )
  47985. _programLayers.enable( 15 );
  47986. if ( parameters.anisotropy )
  47987. _programLayers.enable( 16 );
  47988. if ( parameters.alphaHash )
  47989. _programLayers.enable( 17 );
  47990. if ( parameters.batching )
  47991. _programLayers.enable( 18 );
  47992. if ( parameters.dispersion )
  47993. _programLayers.enable( 19 );
  47994. if ( parameters.batchingColor )
  47995. _programLayers.enable( 20 );
  47996. if ( parameters.gradientMap )
  47997. _programLayers.enable( 21 );
  47998. array.push( _programLayers.mask );
  47999. _programLayers.disableAll();
  48000. if ( parameters.fog )
  48001. _programLayers.enable( 0 );
  48002. if ( parameters.useFog )
  48003. _programLayers.enable( 1 );
  48004. if ( parameters.flatShading )
  48005. _programLayers.enable( 2 );
  48006. if ( parameters.logarithmicDepthBuffer )
  48007. _programLayers.enable( 3 );
  48008. if ( parameters.reversedDepthBuffer )
  48009. _programLayers.enable( 4 );
  48010. if ( parameters.skinning )
  48011. _programLayers.enable( 5 );
  48012. if ( parameters.morphTargets )
  48013. _programLayers.enable( 6 );
  48014. if ( parameters.morphNormals )
  48015. _programLayers.enable( 7 );
  48016. if ( parameters.morphColors )
  48017. _programLayers.enable( 8 );
  48018. if ( parameters.premultipliedAlpha )
  48019. _programLayers.enable( 9 );
  48020. if ( parameters.shadowMapEnabled )
  48021. _programLayers.enable( 10 );
  48022. if ( parameters.doubleSided )
  48023. _programLayers.enable( 11 );
  48024. if ( parameters.flipSided )
  48025. _programLayers.enable( 12 );
  48026. if ( parameters.useDepthPacking )
  48027. _programLayers.enable( 13 );
  48028. if ( parameters.dithering )
  48029. _programLayers.enable( 14 );
  48030. if ( parameters.transmission )
  48031. _programLayers.enable( 15 );
  48032. if ( parameters.sheen )
  48033. _programLayers.enable( 16 );
  48034. if ( parameters.opaque )
  48035. _programLayers.enable( 17 );
  48036. if ( parameters.pointsUvs )
  48037. _programLayers.enable( 18 );
  48038. if ( parameters.decodeVideoTexture )
  48039. _programLayers.enable( 19 );
  48040. if ( parameters.decodeVideoTextureEmissive )
  48041. _programLayers.enable( 20 );
  48042. if ( parameters.alphaToCoverage )
  48043. _programLayers.enable( 21 );
  48044. array.push( _programLayers.mask );
  48045. }
  48046. function getUniforms( material ) {
  48047. const shaderID = shaderIDs[ material.type ];
  48048. let uniforms;
  48049. if ( shaderID ) {
  48050. const shader = ShaderLib[ shaderID ];
  48051. uniforms = UniformsUtils.clone( shader.uniforms );
  48052. } else {
  48053. uniforms = material.uniforms;
  48054. }
  48055. return uniforms;
  48056. }
  48057. function acquireProgram( parameters, cacheKey ) {
  48058. let program = programsMap.get( cacheKey );
  48059. if ( program !== undefined ) {
  48060. ++ program.usedTimes;
  48061. } else {
  48062. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  48063. programs.push( program );
  48064. programsMap.set( cacheKey, program );
  48065. }
  48066. return program;
  48067. }
  48068. function releaseProgram( program ) {
  48069. if ( -- program.usedTimes === 0 ) {
  48070. // Remove from unordered set
  48071. const i = programs.indexOf( program );
  48072. programs[ i ] = programs[ programs.length - 1 ];
  48073. programs.pop();
  48074. // Remove from map
  48075. programsMap.delete( program.cacheKey );
  48076. // Free WebGL resources
  48077. program.destroy();
  48078. }
  48079. }
  48080. function releaseShaderCache( material ) {
  48081. _customShaders.remove( material );
  48082. }
  48083. function dispose() {
  48084. _customShaders.dispose();
  48085. }
  48086. return {
  48087. getParameters: getParameters,
  48088. getProgramCacheKey: getProgramCacheKey,
  48089. getUniforms: getUniforms,
  48090. acquireProgram: acquireProgram,
  48091. releaseProgram: releaseProgram,
  48092. releaseShaderCache: releaseShaderCache,
  48093. // Exposed for resource monitoring & error feedback via renderer.info:
  48094. programs: programs,
  48095. dispose: dispose
  48096. };
  48097. }
  48098. function WebGLProperties() {
  48099. let properties = new WeakMap();
  48100. function has( object ) {
  48101. return properties.has( object );
  48102. }
  48103. function get( object ) {
  48104. let map = properties.get( object );
  48105. if ( map === undefined ) {
  48106. map = {};
  48107. properties.set( object, map );
  48108. }
  48109. return map;
  48110. }
  48111. function remove( object ) {
  48112. properties.delete( object );
  48113. }
  48114. function update( object, key, value ) {
  48115. properties.get( object )[ key ] = value;
  48116. }
  48117. function dispose() {
  48118. properties = new WeakMap();
  48119. }
  48120. return {
  48121. has: has,
  48122. get: get,
  48123. remove: remove,
  48124. update: update,
  48125. dispose: dispose
  48126. };
  48127. }
  48128. function painterSortStable( a, b ) {
  48129. if ( a.groupOrder !== b.groupOrder ) {
  48130. return a.groupOrder - b.groupOrder;
  48131. } else if ( a.renderOrder !== b.renderOrder ) {
  48132. return a.renderOrder - b.renderOrder;
  48133. } else if ( a.material.id !== b.material.id ) {
  48134. return a.material.id - b.material.id;
  48135. } else if ( a.materialVariant !== b.materialVariant ) {
  48136. return a.materialVariant - b.materialVariant;
  48137. } else if ( a.z !== b.z ) {
  48138. return a.z - b.z;
  48139. } else {
  48140. return a.id - b.id;
  48141. }
  48142. }
  48143. function reversePainterSortStable( a, b ) {
  48144. if ( a.groupOrder !== b.groupOrder ) {
  48145. return a.groupOrder - b.groupOrder;
  48146. } else if ( a.renderOrder !== b.renderOrder ) {
  48147. return a.renderOrder - b.renderOrder;
  48148. } else if ( a.z !== b.z ) {
  48149. return b.z - a.z;
  48150. } else {
  48151. return a.id - b.id;
  48152. }
  48153. }
  48154. function WebGLRenderList() {
  48155. const renderItems = [];
  48156. let renderItemsIndex = 0;
  48157. const opaque = [];
  48158. const transmissive = [];
  48159. const transparent = [];
  48160. function init() {
  48161. renderItemsIndex = 0;
  48162. opaque.length = 0;
  48163. transmissive.length = 0;
  48164. transparent.length = 0;
  48165. }
  48166. function materialVariant( object ) {
  48167. let variant = 0;
  48168. if ( object.isInstancedMesh ) variant += 2;
  48169. if ( object.isSkinnedMesh ) variant += 1;
  48170. return variant;
  48171. }
  48172. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  48173. let renderItem = renderItems[ renderItemsIndex ];
  48174. if ( renderItem === undefined ) {
  48175. renderItem = {
  48176. id: object.id,
  48177. object: object,
  48178. geometry: geometry,
  48179. material: material,
  48180. materialVariant: materialVariant( object ),
  48181. groupOrder: groupOrder,
  48182. renderOrder: object.renderOrder,
  48183. z: z,
  48184. group: group
  48185. };
  48186. renderItems[ renderItemsIndex ] = renderItem;
  48187. } else {
  48188. renderItem.id = object.id;
  48189. renderItem.object = object;
  48190. renderItem.geometry = geometry;
  48191. renderItem.material = material;
  48192. renderItem.materialVariant = materialVariant( object );
  48193. renderItem.groupOrder = groupOrder;
  48194. renderItem.renderOrder = object.renderOrder;
  48195. renderItem.z = z;
  48196. renderItem.group = group;
  48197. }
  48198. renderItemsIndex ++;
  48199. return renderItem;
  48200. }
  48201. function push( object, geometry, material, groupOrder, z, group ) {
  48202. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  48203. if ( material.transmission > 0.0 ) {
  48204. transmissive.push( renderItem );
  48205. } else if ( material.transparent === true ) {
  48206. transparent.push( renderItem );
  48207. } else {
  48208. opaque.push( renderItem );
  48209. }
  48210. }
  48211. function unshift( object, geometry, material, groupOrder, z, group ) {
  48212. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  48213. if ( material.transmission > 0.0 ) {
  48214. transmissive.unshift( renderItem );
  48215. } else if ( material.transparent === true ) {
  48216. transparent.unshift( renderItem );
  48217. } else {
  48218. opaque.unshift( renderItem );
  48219. }
  48220. }
  48221. function sort( customOpaqueSort, customTransparentSort ) {
  48222. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  48223. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  48224. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  48225. }
  48226. function finish() {
  48227. // Clear references from inactive renderItems in the list
  48228. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  48229. const renderItem = renderItems[ i ];
  48230. if ( renderItem.id === null ) break;
  48231. renderItem.id = null;
  48232. renderItem.object = null;
  48233. renderItem.geometry = null;
  48234. renderItem.material = null;
  48235. renderItem.group = null;
  48236. }
  48237. }
  48238. return {
  48239. opaque: opaque,
  48240. transmissive: transmissive,
  48241. transparent: transparent,
  48242. init: init,
  48243. push: push,
  48244. unshift: unshift,
  48245. finish: finish,
  48246. sort: sort
  48247. };
  48248. }
  48249. function WebGLRenderLists() {
  48250. let lists = new WeakMap();
  48251. function get( scene, renderCallDepth ) {
  48252. const listArray = lists.get( scene );
  48253. let list;
  48254. if ( listArray === undefined ) {
  48255. list = new WebGLRenderList();
  48256. lists.set( scene, [ list ] );
  48257. } else {
  48258. if ( renderCallDepth >= listArray.length ) {
  48259. list = new WebGLRenderList();
  48260. listArray.push( list );
  48261. } else {
  48262. list = listArray[ renderCallDepth ];
  48263. }
  48264. }
  48265. return list;
  48266. }
  48267. function dispose() {
  48268. lists = new WeakMap();
  48269. }
  48270. return {
  48271. get: get,
  48272. dispose: dispose
  48273. };
  48274. }
  48275. function UniformsCache() {
  48276. const lights = {};
  48277. return {
  48278. get: function ( light ) {
  48279. if ( lights[ light.id ] !== undefined ) {
  48280. return lights[ light.id ];
  48281. }
  48282. let uniforms;
  48283. switch ( light.type ) {
  48284. case 'DirectionalLight':
  48285. uniforms = {
  48286. direction: new Vector3(),
  48287. color: new Color()
  48288. };
  48289. break;
  48290. case 'SpotLight':
  48291. uniforms = {
  48292. position: new Vector3(),
  48293. direction: new Vector3(),
  48294. color: new Color(),
  48295. distance: 0,
  48296. coneCos: 0,
  48297. penumbraCos: 0,
  48298. decay: 0
  48299. };
  48300. break;
  48301. case 'PointLight':
  48302. uniforms = {
  48303. position: new Vector3(),
  48304. color: new Color(),
  48305. distance: 0,
  48306. decay: 0
  48307. };
  48308. break;
  48309. case 'HemisphereLight':
  48310. uniforms = {
  48311. direction: new Vector3(),
  48312. skyColor: new Color(),
  48313. groundColor: new Color()
  48314. };
  48315. break;
  48316. case 'RectAreaLight':
  48317. uniforms = {
  48318. color: new Color(),
  48319. position: new Vector3(),
  48320. halfWidth: new Vector3(),
  48321. halfHeight: new Vector3()
  48322. };
  48323. break;
  48324. }
  48325. lights[ light.id ] = uniforms;
  48326. return uniforms;
  48327. }
  48328. };
  48329. }
  48330. function ShadowUniformsCache() {
  48331. const lights = {};
  48332. return {
  48333. get: function ( light ) {
  48334. if ( lights[ light.id ] !== undefined ) {
  48335. return lights[ light.id ];
  48336. }
  48337. let uniforms;
  48338. switch ( light.type ) {
  48339. case 'DirectionalLight':
  48340. uniforms = {
  48341. shadowIntensity: 1,
  48342. shadowBias: 0,
  48343. shadowNormalBias: 0,
  48344. shadowRadius: 1,
  48345. shadowMapSize: new Vector2()
  48346. };
  48347. break;
  48348. case 'SpotLight':
  48349. uniforms = {
  48350. shadowIntensity: 1,
  48351. shadowBias: 0,
  48352. shadowNormalBias: 0,
  48353. shadowRadius: 1,
  48354. shadowMapSize: new Vector2()
  48355. };
  48356. break;
  48357. case 'PointLight':
  48358. uniforms = {
  48359. shadowIntensity: 1,
  48360. shadowBias: 0,
  48361. shadowNormalBias: 0,
  48362. shadowRadius: 1,
  48363. shadowMapSize: new Vector2(),
  48364. shadowCameraNear: 1,
  48365. shadowCameraFar: 1000
  48366. };
  48367. break;
  48368. // TODO (abelnation): set RectAreaLight shadow uniforms
  48369. }
  48370. lights[ light.id ] = uniforms;
  48371. return uniforms;
  48372. }
  48373. };
  48374. }
  48375. let nextVersion = 0;
  48376. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  48377. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  48378. }
  48379. function WebGLLights( extensions ) {
  48380. const cache = new UniformsCache();
  48381. const shadowCache = ShadowUniformsCache();
  48382. const state = {
  48383. version: 0,
  48384. hash: {
  48385. directionalLength: -1,
  48386. pointLength: -1,
  48387. spotLength: -1,
  48388. rectAreaLength: -1,
  48389. hemiLength: -1,
  48390. numDirectionalShadows: -1,
  48391. numPointShadows: -1,
  48392. numSpotShadows: -1,
  48393. numSpotMaps: -1,
  48394. numLightProbes: -1
  48395. },
  48396. ambient: [ 0, 0, 0 ],
  48397. probe: [],
  48398. directional: [],
  48399. directionalShadow: [],
  48400. directionalShadowMap: [],
  48401. directionalShadowMatrix: [],
  48402. spot: [],
  48403. spotLightMap: [],
  48404. spotShadow: [],
  48405. spotShadowMap: [],
  48406. spotLightMatrix: [],
  48407. rectArea: [],
  48408. rectAreaLTC1: null,
  48409. rectAreaLTC2: null,
  48410. point: [],
  48411. pointShadow: [],
  48412. pointShadowMap: [],
  48413. pointShadowMatrix: [],
  48414. hemi: [],
  48415. numSpotLightShadowsWithMaps: 0,
  48416. numLightProbes: 0
  48417. };
  48418. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  48419. const vector3 = new Vector3();
  48420. const matrix4 = new Matrix4();
  48421. const matrix42 = new Matrix4();
  48422. function setup( lights ) {
  48423. let r = 0, g = 0, b = 0;
  48424. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  48425. let directionalLength = 0;
  48426. let pointLength = 0;
  48427. let spotLength = 0;
  48428. let rectAreaLength = 0;
  48429. let hemiLength = 0;
  48430. let numDirectionalShadows = 0;
  48431. let numPointShadows = 0;
  48432. let numSpotShadows = 0;
  48433. let numSpotMaps = 0;
  48434. let numSpotShadowsWithMaps = 0;
  48435. let numLightProbes = 0;
  48436. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  48437. lights.sort( shadowCastingAndTexturingLightsFirst );
  48438. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48439. const light = lights[ i ];
  48440. const color = light.color;
  48441. const intensity = light.intensity;
  48442. const distance = light.distance;
  48443. let shadowMap = null;
  48444. if ( light.shadow && light.shadow.map ) {
  48445. if ( light.shadow.map.texture.format === RGFormat ) {
  48446. // VSM uses color texture with blurred mean/std_dev
  48447. shadowMap = light.shadow.map.texture;
  48448. } else {
  48449. // Other types use depth texture
  48450. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  48451. }
  48452. }
  48453. if ( light.isAmbientLight ) {
  48454. r += color.r * intensity;
  48455. g += color.g * intensity;
  48456. b += color.b * intensity;
  48457. } else if ( light.isLightProbe ) {
  48458. for ( let j = 0; j < 9; j ++ ) {
  48459. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  48460. }
  48461. numLightProbes ++;
  48462. } else if ( light.isDirectionalLight ) {
  48463. const uniforms = cache.get( light );
  48464. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48465. if ( light.castShadow ) {
  48466. const shadow = light.shadow;
  48467. const shadowUniforms = shadowCache.get( light );
  48468. shadowUniforms.shadowIntensity = shadow.intensity;
  48469. shadowUniforms.shadowBias = shadow.bias;
  48470. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48471. shadowUniforms.shadowRadius = shadow.radius;
  48472. shadowUniforms.shadowMapSize = shadow.mapSize;
  48473. state.directionalShadow[ directionalLength ] = shadowUniforms;
  48474. state.directionalShadowMap[ directionalLength ] = shadowMap;
  48475. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  48476. numDirectionalShadows ++;
  48477. }
  48478. state.directional[ directionalLength ] = uniforms;
  48479. directionalLength ++;
  48480. } else if ( light.isSpotLight ) {
  48481. const uniforms = cache.get( light );
  48482. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48483. uniforms.color.copy( color ).multiplyScalar( intensity );
  48484. uniforms.distance = distance;
  48485. uniforms.coneCos = Math.cos( light.angle );
  48486. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  48487. uniforms.decay = light.decay;
  48488. state.spot[ spotLength ] = uniforms;
  48489. const shadow = light.shadow;
  48490. if ( light.map ) {
  48491. state.spotLightMap[ numSpotMaps ] = light.map;
  48492. numSpotMaps ++;
  48493. // make sure the lightMatrix is up to date
  48494. // TODO : do it if required only
  48495. shadow.updateMatrices( light );
  48496. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  48497. }
  48498. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  48499. if ( light.castShadow ) {
  48500. const shadowUniforms = shadowCache.get( light );
  48501. shadowUniforms.shadowIntensity = shadow.intensity;
  48502. shadowUniforms.shadowBias = shadow.bias;
  48503. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48504. shadowUniforms.shadowRadius = shadow.radius;
  48505. shadowUniforms.shadowMapSize = shadow.mapSize;
  48506. state.spotShadow[ spotLength ] = shadowUniforms;
  48507. state.spotShadowMap[ spotLength ] = shadowMap;
  48508. numSpotShadows ++;
  48509. }
  48510. spotLength ++;
  48511. } else if ( light.isRectAreaLight ) {
  48512. const uniforms = cache.get( light );
  48513. uniforms.color.copy( color ).multiplyScalar( intensity );
  48514. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48515. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48516. state.rectArea[ rectAreaLength ] = uniforms;
  48517. rectAreaLength ++;
  48518. } else if ( light.isPointLight ) {
  48519. const uniforms = cache.get( light );
  48520. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48521. uniforms.distance = light.distance;
  48522. uniforms.decay = light.decay;
  48523. if ( light.castShadow ) {
  48524. const shadow = light.shadow;
  48525. const shadowUniforms = shadowCache.get( light );
  48526. shadowUniforms.shadowIntensity = shadow.intensity;
  48527. shadowUniforms.shadowBias = shadow.bias;
  48528. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48529. shadowUniforms.shadowRadius = shadow.radius;
  48530. shadowUniforms.shadowMapSize = shadow.mapSize;
  48531. shadowUniforms.shadowCameraNear = shadow.camera.near;
  48532. shadowUniforms.shadowCameraFar = shadow.camera.far;
  48533. state.pointShadow[ pointLength ] = shadowUniforms;
  48534. state.pointShadowMap[ pointLength ] = shadowMap;
  48535. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  48536. numPointShadows ++;
  48537. }
  48538. state.point[ pointLength ] = uniforms;
  48539. pointLength ++;
  48540. } else if ( light.isHemisphereLight ) {
  48541. const uniforms = cache.get( light );
  48542. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  48543. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  48544. state.hemi[ hemiLength ] = uniforms;
  48545. hemiLength ++;
  48546. }
  48547. }
  48548. if ( rectAreaLength > 0 ) {
  48549. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  48550. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  48551. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  48552. } else {
  48553. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  48554. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  48555. }
  48556. }
  48557. state.ambient[ 0 ] = r;
  48558. state.ambient[ 1 ] = g;
  48559. state.ambient[ 2 ] = b;
  48560. const hash = state.hash;
  48561. if ( hash.directionalLength !== directionalLength ||
  48562. hash.pointLength !== pointLength ||
  48563. hash.spotLength !== spotLength ||
  48564. hash.rectAreaLength !== rectAreaLength ||
  48565. hash.hemiLength !== hemiLength ||
  48566. hash.numDirectionalShadows !== numDirectionalShadows ||
  48567. hash.numPointShadows !== numPointShadows ||
  48568. hash.numSpotShadows !== numSpotShadows ||
  48569. hash.numSpotMaps !== numSpotMaps ||
  48570. hash.numLightProbes !== numLightProbes ) {
  48571. state.directional.length = directionalLength;
  48572. state.spot.length = spotLength;
  48573. state.rectArea.length = rectAreaLength;
  48574. state.point.length = pointLength;
  48575. state.hemi.length = hemiLength;
  48576. state.directionalShadow.length = numDirectionalShadows;
  48577. state.directionalShadowMap.length = numDirectionalShadows;
  48578. state.pointShadow.length = numPointShadows;
  48579. state.pointShadowMap.length = numPointShadows;
  48580. state.spotShadow.length = numSpotShadows;
  48581. state.spotShadowMap.length = numSpotShadows;
  48582. state.directionalShadowMatrix.length = numDirectionalShadows;
  48583. state.pointShadowMatrix.length = numPointShadows;
  48584. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48585. state.spotLightMap.length = numSpotMaps;
  48586. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48587. state.numLightProbes = numLightProbes;
  48588. hash.directionalLength = directionalLength;
  48589. hash.pointLength = pointLength;
  48590. hash.spotLength = spotLength;
  48591. hash.rectAreaLength = rectAreaLength;
  48592. hash.hemiLength = hemiLength;
  48593. hash.numDirectionalShadows = numDirectionalShadows;
  48594. hash.numPointShadows = numPointShadows;
  48595. hash.numSpotShadows = numSpotShadows;
  48596. hash.numSpotMaps = numSpotMaps;
  48597. hash.numLightProbes = numLightProbes;
  48598. state.version = nextVersion ++;
  48599. }
  48600. }
  48601. function setupView( lights, camera ) {
  48602. let directionalLength = 0;
  48603. let pointLength = 0;
  48604. let spotLength = 0;
  48605. let rectAreaLength = 0;
  48606. let hemiLength = 0;
  48607. const viewMatrix = camera.matrixWorldInverse;
  48608. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48609. const light = lights[ i ];
  48610. if ( light.isDirectionalLight ) {
  48611. const uniforms = state.directional[ directionalLength ];
  48612. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48613. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48614. uniforms.direction.sub( vector3 );
  48615. uniforms.direction.transformDirection( viewMatrix );
  48616. directionalLength ++;
  48617. } else if ( light.isSpotLight ) {
  48618. const uniforms = state.spot[ spotLength ];
  48619. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48620. uniforms.position.applyMatrix4( viewMatrix );
  48621. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48622. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48623. uniforms.direction.sub( vector3 );
  48624. uniforms.direction.transformDirection( viewMatrix );
  48625. spotLength ++;
  48626. } else if ( light.isRectAreaLight ) {
  48627. const uniforms = state.rectArea[ rectAreaLength ];
  48628. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48629. uniforms.position.applyMatrix4( viewMatrix );
  48630. // extract local rotation of light to derive width/height half vectors
  48631. matrix42.identity();
  48632. matrix4.copy( light.matrixWorld );
  48633. matrix4.premultiply( viewMatrix );
  48634. matrix42.extractRotation( matrix4 );
  48635. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48636. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48637. uniforms.halfWidth.applyMatrix4( matrix42 );
  48638. uniforms.halfHeight.applyMatrix4( matrix42 );
  48639. rectAreaLength ++;
  48640. } else if ( light.isPointLight ) {
  48641. const uniforms = state.point[ pointLength ];
  48642. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48643. uniforms.position.applyMatrix4( viewMatrix );
  48644. pointLength ++;
  48645. } else if ( light.isHemisphereLight ) {
  48646. const uniforms = state.hemi[ hemiLength ];
  48647. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48648. uniforms.direction.transformDirection( viewMatrix );
  48649. hemiLength ++;
  48650. }
  48651. }
  48652. }
  48653. return {
  48654. setup: setup,
  48655. setupView: setupView,
  48656. state: state
  48657. };
  48658. }
  48659. function WebGLRenderState( extensions ) {
  48660. const lights = new WebGLLights( extensions );
  48661. const lightsArray = [];
  48662. const shadowsArray = [];
  48663. function init( camera ) {
  48664. state.camera = camera;
  48665. lightsArray.length = 0;
  48666. shadowsArray.length = 0;
  48667. }
  48668. function pushLight( light ) {
  48669. lightsArray.push( light );
  48670. }
  48671. function pushShadow( shadowLight ) {
  48672. shadowsArray.push( shadowLight );
  48673. }
  48674. function setupLights() {
  48675. lights.setup( lightsArray );
  48676. }
  48677. function setupLightsView( camera ) {
  48678. lights.setupView( lightsArray, camera );
  48679. }
  48680. const state = {
  48681. lightsArray: lightsArray,
  48682. shadowsArray: shadowsArray,
  48683. camera: null,
  48684. lights: lights,
  48685. transmissionRenderTarget: {}
  48686. };
  48687. return {
  48688. init: init,
  48689. state: state,
  48690. setupLights: setupLights,
  48691. setupLightsView: setupLightsView,
  48692. pushLight: pushLight,
  48693. pushShadow: pushShadow
  48694. };
  48695. }
  48696. function WebGLRenderStates( extensions ) {
  48697. let renderStates = new WeakMap();
  48698. function get( scene, renderCallDepth = 0 ) {
  48699. const renderStateArray = renderStates.get( scene );
  48700. let renderState;
  48701. if ( renderStateArray === undefined ) {
  48702. renderState = new WebGLRenderState( extensions );
  48703. renderStates.set( scene, [ renderState ] );
  48704. } else {
  48705. if ( renderCallDepth >= renderStateArray.length ) {
  48706. renderState = new WebGLRenderState( extensions );
  48707. renderStateArray.push( renderState );
  48708. } else {
  48709. renderState = renderStateArray[ renderCallDepth ];
  48710. }
  48711. }
  48712. return renderState;
  48713. }
  48714. function dispose() {
  48715. renderStates = new WeakMap();
  48716. }
  48717. return {
  48718. get: get,
  48719. dispose: dispose
  48720. };
  48721. }
  48722. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48723. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}";
  48724. const _cubeDirections = [
  48725. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  48726. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  48727. ];
  48728. const _cubeUps = [
  48729. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  48730. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  48731. ];
  48732. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  48733. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  48734. const _lookTarget = /*@__PURE__*/ new Vector3();
  48735. function WebGLShadowMap( renderer, objects, capabilities ) {
  48736. let _frustum = new Frustum();
  48737. const _shadowMapSize = new Vector2(),
  48738. _viewportSize = new Vector2(),
  48739. _viewport = new Vector4(),
  48740. _depthMaterial = new MeshDepthMaterial(),
  48741. _distanceMaterial = new MeshDistanceMaterial(),
  48742. _materialCache = {},
  48743. _maxTextureSize = capabilities.maxTextureSize;
  48744. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48745. const shadowMaterialVertical = new ShaderMaterial( {
  48746. defines: {
  48747. VSM_SAMPLES: 8
  48748. },
  48749. uniforms: {
  48750. shadow_pass: { value: null },
  48751. resolution: { value: new Vector2() },
  48752. radius: { value: 4.0 }
  48753. },
  48754. vertexShader: vertex,
  48755. fragmentShader: fragment
  48756. } );
  48757. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48758. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48759. const fullScreenTri = new BufferGeometry();
  48760. fullScreenTri.setAttribute(
  48761. 'position',
  48762. new BufferAttribute(
  48763. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48764. 3
  48765. )
  48766. );
  48767. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48768. const scope = this;
  48769. this.enabled = false;
  48770. this.autoUpdate = true;
  48771. this.needsUpdate = false;
  48772. this.type = PCFShadowMap;
  48773. let _previousType = this.type;
  48774. this.render = function ( lights, scene, camera ) {
  48775. if ( scope.enabled === false ) return;
  48776. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48777. if ( lights.length === 0 ) return;
  48778. if ( this.type === PCFSoftShadowMap ) {
  48779. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48780. this.type = PCFShadowMap;
  48781. }
  48782. const currentRenderTarget = renderer.getRenderTarget();
  48783. const activeCubeFace = renderer.getActiveCubeFace();
  48784. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48785. const _state = renderer.state;
  48786. // Set GL state for depth map.
  48787. _state.setBlending( NoBlending );
  48788. if ( _state.buffers.depth.getReversed() === true ) {
  48789. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48790. } else {
  48791. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48792. }
  48793. _state.buffers.depth.setTest( true );
  48794. _state.setScissorTest( false );
  48795. // check for shadow map type changes
  48796. const typeChanged = _previousType !== this.type;
  48797. // When shadow map type changes, materials need recompilation because sampler types change
  48798. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48799. if ( typeChanged ) {
  48800. scene.traverse( function ( object ) {
  48801. if ( object.material ) {
  48802. if ( Array.isArray( object.material ) ) {
  48803. object.material.forEach( mat => mat.needsUpdate = true );
  48804. } else {
  48805. object.material.needsUpdate = true;
  48806. }
  48807. }
  48808. } );
  48809. }
  48810. // render depth map
  48811. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48812. const light = lights[ i ];
  48813. const shadow = light.shadow;
  48814. if ( shadow === undefined ) {
  48815. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48816. continue;
  48817. }
  48818. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48819. _shadowMapSize.copy( shadow.mapSize );
  48820. const shadowFrameExtents = shadow.getFrameExtents();
  48821. _shadowMapSize.multiply( shadowFrameExtents );
  48822. _viewportSize.copy( shadow.mapSize );
  48823. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48824. if ( _shadowMapSize.x > _maxTextureSize ) {
  48825. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48826. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48827. shadow.mapSize.x = _viewportSize.x;
  48828. }
  48829. if ( _shadowMapSize.y > _maxTextureSize ) {
  48830. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48831. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48832. shadow.mapSize.y = _viewportSize.y;
  48833. }
  48834. }
  48835. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48836. shadow.camera._reversedDepth = reversedDepthBuffer;
  48837. if ( shadow.map === null || typeChanged === true ) {
  48838. if ( shadow.map !== null ) {
  48839. if ( shadow.map.depthTexture !== null ) {
  48840. shadow.map.depthTexture.dispose();
  48841. shadow.map.depthTexture = null;
  48842. }
  48843. shadow.map.dispose();
  48844. }
  48845. if ( this.type === VSMShadowMap ) {
  48846. if ( light.isPointLight ) {
  48847. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48848. continue;
  48849. }
  48850. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48851. format: RGFormat,
  48852. type: HalfFloatType,
  48853. minFilter: LinearFilter,
  48854. magFilter: LinearFilter,
  48855. generateMipmaps: false
  48856. } );
  48857. shadow.map.texture.name = light.name + '.shadowMap';
  48858. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  48859. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  48860. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  48861. shadow.map.depthTexture.format = DepthFormat;
  48862. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  48863. shadow.map.depthTexture.minFilter = NearestFilter;
  48864. shadow.map.depthTexture.magFilter = NearestFilter;
  48865. } else {
  48866. if ( light.isPointLight ) {
  48867. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48868. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48869. } else {
  48870. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48871. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48872. }
  48873. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48874. shadow.map.depthTexture.format = DepthFormat;
  48875. if ( this.type === PCFShadowMap ) {
  48876. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48877. shadow.map.depthTexture.minFilter = LinearFilter;
  48878. shadow.map.depthTexture.magFilter = LinearFilter;
  48879. } else {
  48880. shadow.map.depthTexture.compareFunction = null;
  48881. shadow.map.depthTexture.minFilter = NearestFilter;
  48882. shadow.map.depthTexture.magFilter = NearestFilter;
  48883. }
  48884. }
  48885. shadow.camera.updateProjectionMatrix();
  48886. }
  48887. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48888. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48889. for ( let face = 0; face < faceCount; face ++ ) {
  48890. // For cube render targets, render to each face separately
  48891. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48892. renderer.setRenderTarget( shadow.map, face );
  48893. renderer.clear();
  48894. } else {
  48895. // For 2D render targets, use viewports
  48896. if ( face === 0 ) {
  48897. renderer.setRenderTarget( shadow.map );
  48898. renderer.clear();
  48899. }
  48900. const viewport = shadow.getViewport( face );
  48901. _viewport.set(
  48902. _viewportSize.x * viewport.x,
  48903. _viewportSize.y * viewport.y,
  48904. _viewportSize.x * viewport.z,
  48905. _viewportSize.y * viewport.w
  48906. );
  48907. _state.viewport( _viewport );
  48908. }
  48909. if ( light.isPointLight ) {
  48910. const camera = shadow.camera;
  48911. const shadowMatrix = shadow.matrix;
  48912. const far = light.distance || camera.far;
  48913. if ( far !== camera.far ) {
  48914. camera.far = far;
  48915. camera.updateProjectionMatrix();
  48916. }
  48917. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  48918. camera.position.copy( _lightPositionWorld );
  48919. _lookTarget.copy( camera.position );
  48920. _lookTarget.add( _cubeDirections[ face ] );
  48921. camera.up.copy( _cubeUps[ face ] );
  48922. camera.lookAt( _lookTarget );
  48923. camera.updateMatrixWorld();
  48924. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  48925. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  48926. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  48927. } else {
  48928. shadow.updateMatrices( light );
  48929. }
  48930. _frustum = shadow.getFrustum();
  48931. renderObject( scene, camera, shadow.camera, light, this.type );
  48932. }
  48933. // do blur pass for VSM
  48934. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  48935. VSMPass( shadow, camera );
  48936. }
  48937. shadow.needsUpdate = false;
  48938. }
  48939. _previousType = this.type;
  48940. scope.needsUpdate = false;
  48941. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  48942. };
  48943. function VSMPass( shadow, camera ) {
  48944. const geometry = objects.update( fullScreenMesh );
  48945. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  48946. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  48947. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  48948. shadowMaterialVertical.needsUpdate = true;
  48949. shadowMaterialHorizontal.needsUpdate = true;
  48950. }
  48951. if ( shadow.mapPass === null ) {
  48952. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48953. format: RGFormat,
  48954. type: HalfFloatType
  48955. } );
  48956. }
  48957. // vertical pass - read from native depth texture
  48958. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  48959. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  48960. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  48961. renderer.setRenderTarget( shadow.mapPass );
  48962. renderer.clear();
  48963. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  48964. // horizontal pass
  48965. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  48966. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  48967. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  48968. renderer.setRenderTarget( shadow.map );
  48969. renderer.clear();
  48970. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  48971. }
  48972. function getDepthMaterial( object, material, light, type ) {
  48973. let result = null;
  48974. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  48975. if ( customMaterial !== undefined ) {
  48976. result = customMaterial;
  48977. } else {
  48978. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  48979. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  48980. ( material.displacementMap && material.displacementScale !== 0 ) ||
  48981. ( material.alphaMap && material.alphaTest > 0 ) ||
  48982. ( material.map && material.alphaTest > 0 ) ||
  48983. ( material.alphaToCoverage === true ) ) {
  48984. // in this case we need a unique material instance reflecting the
  48985. // appropriate state
  48986. const keyA = result.uuid, keyB = material.uuid;
  48987. let materialsForVariant = _materialCache[ keyA ];
  48988. if ( materialsForVariant === undefined ) {
  48989. materialsForVariant = {};
  48990. _materialCache[ keyA ] = materialsForVariant;
  48991. }
  48992. let cachedMaterial = materialsForVariant[ keyB ];
  48993. if ( cachedMaterial === undefined ) {
  48994. cachedMaterial = result.clone();
  48995. materialsForVariant[ keyB ] = cachedMaterial;
  48996. material.addEventListener( 'dispose', onMaterialDispose );
  48997. }
  48998. result = cachedMaterial;
  48999. }
  49000. }
  49001. result.visible = material.visible;
  49002. result.wireframe = material.wireframe;
  49003. if ( type === VSMShadowMap ) {
  49004. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  49005. } else {
  49006. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  49007. }
  49008. result.alphaMap = material.alphaMap;
  49009. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  49010. result.map = material.map;
  49011. result.clipShadows = material.clipShadows;
  49012. result.clippingPlanes = material.clippingPlanes;
  49013. result.clipIntersection = material.clipIntersection;
  49014. result.displacementMap = material.displacementMap;
  49015. result.displacementScale = material.displacementScale;
  49016. result.displacementBias = material.displacementBias;
  49017. result.wireframeLinewidth = material.wireframeLinewidth;
  49018. result.linewidth = material.linewidth;
  49019. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  49020. const materialProperties = renderer.properties.get( result );
  49021. materialProperties.light = light;
  49022. }
  49023. return result;
  49024. }
  49025. function renderObject( object, camera, shadowCamera, light, type ) {
  49026. if ( object.visible === false ) return;
  49027. const visible = object.layers.test( camera.layers );
  49028. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  49029. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  49030. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  49031. const geometry = objects.update( object );
  49032. const material = object.material;
  49033. if ( Array.isArray( material ) ) {
  49034. const groups = geometry.groups;
  49035. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  49036. const group = groups[ k ];
  49037. const groupMaterial = material[ group.materialIndex ];
  49038. if ( groupMaterial && groupMaterial.visible ) {
  49039. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  49040. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  49041. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  49042. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  49043. }
  49044. }
  49045. } else if ( material.visible ) {
  49046. const depthMaterial = getDepthMaterial( object, material, light, type );
  49047. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  49048. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  49049. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  49050. }
  49051. }
  49052. }
  49053. const children = object.children;
  49054. for ( let i = 0, l = children.length; i < l; i ++ ) {
  49055. renderObject( children[ i ], camera, shadowCamera, light, type );
  49056. }
  49057. }
  49058. function onMaterialDispose( event ) {
  49059. const material = event.target;
  49060. material.removeEventListener( 'dispose', onMaterialDispose );
  49061. // make sure to remove the unique distance/depth materials used for shadow map rendering
  49062. for ( const id in _materialCache ) {
  49063. const cache = _materialCache[ id ];
  49064. const uuid = event.target.uuid;
  49065. if ( uuid in cache ) {
  49066. const shadowMaterial = cache[ uuid ];
  49067. shadowMaterial.dispose();
  49068. delete cache[ uuid ];
  49069. }
  49070. }
  49071. }
  49072. }
  49073. const reversedFuncs = {
  49074. [ NeverDepth ]: AlwaysDepth,
  49075. [ LessDepth ]: GreaterDepth,
  49076. [ EqualDepth ]: NotEqualDepth,
  49077. [ LessEqualDepth ]: GreaterEqualDepth,
  49078. [ AlwaysDepth ]: NeverDepth,
  49079. [ GreaterDepth ]: LessDepth,
  49080. [ NotEqualDepth ]: EqualDepth,
  49081. [ GreaterEqualDepth ]: LessEqualDepth,
  49082. };
  49083. function WebGLState( gl, extensions ) {
  49084. function ColorBuffer() {
  49085. let locked = false;
  49086. const color = new Vector4();
  49087. let currentColorMask = null;
  49088. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  49089. return {
  49090. setMask: function ( colorMask ) {
  49091. if ( currentColorMask !== colorMask && ! locked ) {
  49092. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  49093. currentColorMask = colorMask;
  49094. }
  49095. },
  49096. setLocked: function ( lock ) {
  49097. locked = lock;
  49098. },
  49099. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  49100. if ( premultipliedAlpha === true ) {
  49101. r *= a; g *= a; b *= a;
  49102. }
  49103. color.set( r, g, b, a );
  49104. if ( currentColorClear.equals( color ) === false ) {
  49105. gl.clearColor( r, g, b, a );
  49106. currentColorClear.copy( color );
  49107. }
  49108. },
  49109. reset: function () {
  49110. locked = false;
  49111. currentColorMask = null;
  49112. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  49113. }
  49114. };
  49115. }
  49116. function DepthBuffer() {
  49117. let locked = false;
  49118. let currentReversed = false;
  49119. let currentDepthMask = null;
  49120. let currentDepthFunc = null;
  49121. let currentDepthClear = null;
  49122. return {
  49123. setReversed: function ( reversed ) {
  49124. if ( currentReversed !== reversed ) {
  49125. const ext = extensions.get( 'EXT_clip_control' );
  49126. if ( reversed ) {
  49127. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  49128. } else {
  49129. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  49130. }
  49131. currentReversed = reversed;
  49132. const oldDepth = currentDepthClear;
  49133. currentDepthClear = null;
  49134. this.setClear( oldDepth );
  49135. }
  49136. },
  49137. getReversed: function () {
  49138. return currentReversed;
  49139. },
  49140. setTest: function ( depthTest ) {
  49141. if ( depthTest ) {
  49142. enable( gl.DEPTH_TEST );
  49143. } else {
  49144. disable( gl.DEPTH_TEST );
  49145. }
  49146. },
  49147. setMask: function ( depthMask ) {
  49148. if ( currentDepthMask !== depthMask && ! locked ) {
  49149. gl.depthMask( depthMask );
  49150. currentDepthMask = depthMask;
  49151. }
  49152. },
  49153. setFunc: function ( depthFunc ) {
  49154. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  49155. if ( currentDepthFunc !== depthFunc ) {
  49156. switch ( depthFunc ) {
  49157. case NeverDepth:
  49158. gl.depthFunc( gl.NEVER );
  49159. break;
  49160. case AlwaysDepth:
  49161. gl.depthFunc( gl.ALWAYS );
  49162. break;
  49163. case LessDepth:
  49164. gl.depthFunc( gl.LESS );
  49165. break;
  49166. case LessEqualDepth:
  49167. gl.depthFunc( gl.LEQUAL );
  49168. break;
  49169. case EqualDepth:
  49170. gl.depthFunc( gl.EQUAL );
  49171. break;
  49172. case GreaterEqualDepth:
  49173. gl.depthFunc( gl.GEQUAL );
  49174. break;
  49175. case GreaterDepth:
  49176. gl.depthFunc( gl.GREATER );
  49177. break;
  49178. case NotEqualDepth:
  49179. gl.depthFunc( gl.NOTEQUAL );
  49180. break;
  49181. default:
  49182. gl.depthFunc( gl.LEQUAL );
  49183. }
  49184. currentDepthFunc = depthFunc;
  49185. }
  49186. },
  49187. setLocked: function ( lock ) {
  49188. locked = lock;
  49189. },
  49190. setClear: function ( depth ) {
  49191. if ( currentDepthClear !== depth ) {
  49192. currentDepthClear = depth;
  49193. if ( currentReversed ) {
  49194. depth = 1 - depth;
  49195. }
  49196. gl.clearDepth( depth );
  49197. }
  49198. },
  49199. reset: function () {
  49200. locked = false;
  49201. currentDepthMask = null;
  49202. currentDepthFunc = null;
  49203. currentDepthClear = null;
  49204. currentReversed = false;
  49205. }
  49206. };
  49207. }
  49208. function StencilBuffer() {
  49209. let locked = false;
  49210. let currentStencilMask = null;
  49211. let currentStencilFunc = null;
  49212. let currentStencilRef = null;
  49213. let currentStencilFuncMask = null;
  49214. let currentStencilFail = null;
  49215. let currentStencilZFail = null;
  49216. let currentStencilZPass = null;
  49217. let currentStencilClear = null;
  49218. return {
  49219. setTest: function ( stencilTest ) {
  49220. if ( ! locked ) {
  49221. if ( stencilTest ) {
  49222. enable( gl.STENCIL_TEST );
  49223. } else {
  49224. disable( gl.STENCIL_TEST );
  49225. }
  49226. }
  49227. },
  49228. setMask: function ( stencilMask ) {
  49229. if ( currentStencilMask !== stencilMask && ! locked ) {
  49230. gl.stencilMask( stencilMask );
  49231. currentStencilMask = stencilMask;
  49232. }
  49233. },
  49234. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  49235. if ( currentStencilFunc !== stencilFunc ||
  49236. currentStencilRef !== stencilRef ||
  49237. currentStencilFuncMask !== stencilMask ) {
  49238. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  49239. currentStencilFunc = stencilFunc;
  49240. currentStencilRef = stencilRef;
  49241. currentStencilFuncMask = stencilMask;
  49242. }
  49243. },
  49244. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  49245. if ( currentStencilFail !== stencilFail ||
  49246. currentStencilZFail !== stencilZFail ||
  49247. currentStencilZPass !== stencilZPass ) {
  49248. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  49249. currentStencilFail = stencilFail;
  49250. currentStencilZFail = stencilZFail;
  49251. currentStencilZPass = stencilZPass;
  49252. }
  49253. },
  49254. setLocked: function ( lock ) {
  49255. locked = lock;
  49256. },
  49257. setClear: function ( stencil ) {
  49258. if ( currentStencilClear !== stencil ) {
  49259. gl.clearStencil( stencil );
  49260. currentStencilClear = stencil;
  49261. }
  49262. },
  49263. reset: function () {
  49264. locked = false;
  49265. currentStencilMask = null;
  49266. currentStencilFunc = null;
  49267. currentStencilRef = null;
  49268. currentStencilFuncMask = null;
  49269. currentStencilFail = null;
  49270. currentStencilZFail = null;
  49271. currentStencilZPass = null;
  49272. currentStencilClear = null;
  49273. }
  49274. };
  49275. }
  49276. //
  49277. const colorBuffer = new ColorBuffer();
  49278. const depthBuffer = new DepthBuffer();
  49279. const stencilBuffer = new StencilBuffer();
  49280. const uboBindings = new WeakMap();
  49281. const uboProgramMap = new WeakMap();
  49282. let enabledCapabilities = {};
  49283. let currentBoundFramebuffers = {};
  49284. let currentDrawbuffers = new WeakMap();
  49285. let defaultDrawbuffers = [];
  49286. let currentProgram = null;
  49287. let currentBlendingEnabled = false;
  49288. let currentBlending = null;
  49289. let currentBlendEquation = null;
  49290. let currentBlendSrc = null;
  49291. let currentBlendDst = null;
  49292. let currentBlendEquationAlpha = null;
  49293. let currentBlendSrcAlpha = null;
  49294. let currentBlendDstAlpha = null;
  49295. let currentBlendColor = new Color( 0, 0, 0 );
  49296. let currentBlendAlpha = 0;
  49297. let currentPremultipledAlpha = false;
  49298. let currentFlipSided = null;
  49299. let currentCullFace = null;
  49300. let currentLineWidth = null;
  49301. let currentPolygonOffsetFactor = null;
  49302. let currentPolygonOffsetUnits = null;
  49303. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  49304. let lineWidthAvailable = false;
  49305. let version = 0;
  49306. const glVersion = gl.getParameter( gl.VERSION );
  49307. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  49308. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  49309. lineWidthAvailable = ( version >= 1.0 );
  49310. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  49311. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  49312. lineWidthAvailable = ( version >= 2.0 );
  49313. }
  49314. let currentTextureSlot = null;
  49315. let currentBoundTextures = {};
  49316. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  49317. const viewportParam = gl.getParameter( gl.VIEWPORT );
  49318. const currentScissor = new Vector4().fromArray( scissorParam );
  49319. const currentViewport = new Vector4().fromArray( viewportParam );
  49320. function createTexture( type, target, count, dimensions ) {
  49321. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  49322. const texture = gl.createTexture();
  49323. gl.bindTexture( type, texture );
  49324. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  49325. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  49326. for ( let i = 0; i < count; i ++ ) {
  49327. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  49328. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49329. } else {
  49330. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49331. }
  49332. }
  49333. return texture;
  49334. }
  49335. const emptyTextures = {};
  49336. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  49337. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  49338. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  49339. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  49340. // init
  49341. colorBuffer.setClear( 0, 0, 0, 1 );
  49342. depthBuffer.setClear( 1 );
  49343. stencilBuffer.setClear( 0 );
  49344. enable( gl.DEPTH_TEST );
  49345. depthBuffer.setFunc( LessEqualDepth );
  49346. setFlipSided( false );
  49347. setCullFace( CullFaceBack );
  49348. enable( gl.CULL_FACE );
  49349. setBlending( NoBlending );
  49350. //
  49351. function enable( id ) {
  49352. if ( enabledCapabilities[ id ] !== true ) {
  49353. gl.enable( id );
  49354. enabledCapabilities[ id ] = true;
  49355. }
  49356. }
  49357. function disable( id ) {
  49358. if ( enabledCapabilities[ id ] !== false ) {
  49359. gl.disable( id );
  49360. enabledCapabilities[ id ] = false;
  49361. }
  49362. }
  49363. function bindFramebuffer( target, framebuffer ) {
  49364. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  49365. gl.bindFramebuffer( target, framebuffer );
  49366. currentBoundFramebuffers[ target ] = framebuffer;
  49367. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  49368. if ( target === gl.DRAW_FRAMEBUFFER ) {
  49369. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  49370. }
  49371. if ( target === gl.FRAMEBUFFER ) {
  49372. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  49373. }
  49374. return true;
  49375. }
  49376. return false;
  49377. }
  49378. function drawBuffers( renderTarget, framebuffer ) {
  49379. let drawBuffers = defaultDrawbuffers;
  49380. let needsUpdate = false;
  49381. if ( renderTarget ) {
  49382. drawBuffers = currentDrawbuffers.get( framebuffer );
  49383. if ( drawBuffers === undefined ) {
  49384. drawBuffers = [];
  49385. currentDrawbuffers.set( framebuffer, drawBuffers );
  49386. }
  49387. const textures = renderTarget.textures;
  49388. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  49389. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49390. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  49391. }
  49392. drawBuffers.length = textures.length;
  49393. needsUpdate = true;
  49394. }
  49395. } else {
  49396. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  49397. drawBuffers[ 0 ] = gl.BACK;
  49398. needsUpdate = true;
  49399. }
  49400. }
  49401. if ( needsUpdate ) {
  49402. gl.drawBuffers( drawBuffers );
  49403. }
  49404. }
  49405. function useProgram( program ) {
  49406. if ( currentProgram !== program ) {
  49407. gl.useProgram( program );
  49408. currentProgram = program;
  49409. return true;
  49410. }
  49411. return false;
  49412. }
  49413. const equationToGL = {
  49414. [ AddEquation ]: gl.FUNC_ADD,
  49415. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  49416. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  49417. };
  49418. equationToGL[ MinEquation ] = gl.MIN;
  49419. equationToGL[ MaxEquation ] = gl.MAX;
  49420. const factorToGL = {
  49421. [ ZeroFactor ]: gl.ZERO,
  49422. [ OneFactor ]: gl.ONE,
  49423. [ SrcColorFactor ]: gl.SRC_COLOR,
  49424. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  49425. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  49426. [ DstColorFactor ]: gl.DST_COLOR,
  49427. [ DstAlphaFactor ]: gl.DST_ALPHA,
  49428. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  49429. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  49430. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  49431. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  49432. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  49433. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  49434. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  49435. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  49436. };
  49437. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  49438. if ( blending === NoBlending ) {
  49439. if ( currentBlendingEnabled === true ) {
  49440. disable( gl.BLEND );
  49441. currentBlendingEnabled = false;
  49442. }
  49443. return;
  49444. }
  49445. if ( currentBlendingEnabled === false ) {
  49446. enable( gl.BLEND );
  49447. currentBlendingEnabled = true;
  49448. }
  49449. if ( blending !== CustomBlending ) {
  49450. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  49451. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  49452. gl.blendEquation( gl.FUNC_ADD );
  49453. currentBlendEquation = AddEquation;
  49454. currentBlendEquationAlpha = AddEquation;
  49455. }
  49456. if ( premultipliedAlpha ) {
  49457. switch ( blending ) {
  49458. case NormalBlending:
  49459. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49460. break;
  49461. case AdditiveBlending:
  49462. gl.blendFunc( gl.ONE, gl.ONE );
  49463. break;
  49464. case SubtractiveBlending:
  49465. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  49466. break;
  49467. case MultiplyBlending:
  49468. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  49469. break;
  49470. default:
  49471. error( 'WebGLState: Invalid blending: ', blending );
  49472. break;
  49473. }
  49474. } else {
  49475. switch ( blending ) {
  49476. case NormalBlending:
  49477. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49478. break;
  49479. case AdditiveBlending:
  49480. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  49481. break;
  49482. case SubtractiveBlending:
  49483. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49484. break;
  49485. case MultiplyBlending:
  49486. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  49487. break;
  49488. default:
  49489. error( 'WebGLState: Invalid blending: ', blending );
  49490. break;
  49491. }
  49492. }
  49493. currentBlendSrc = null;
  49494. currentBlendDst = null;
  49495. currentBlendSrcAlpha = null;
  49496. currentBlendDstAlpha = null;
  49497. currentBlendColor.set( 0, 0, 0 );
  49498. currentBlendAlpha = 0;
  49499. currentBlending = blending;
  49500. currentPremultipledAlpha = premultipliedAlpha;
  49501. }
  49502. return;
  49503. }
  49504. // custom blending
  49505. blendEquationAlpha = blendEquationAlpha || blendEquation;
  49506. blendSrcAlpha = blendSrcAlpha || blendSrc;
  49507. blendDstAlpha = blendDstAlpha || blendDst;
  49508. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  49509. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  49510. currentBlendEquation = blendEquation;
  49511. currentBlendEquationAlpha = blendEquationAlpha;
  49512. }
  49513. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  49514. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  49515. currentBlendSrc = blendSrc;
  49516. currentBlendDst = blendDst;
  49517. currentBlendSrcAlpha = blendSrcAlpha;
  49518. currentBlendDstAlpha = blendDstAlpha;
  49519. }
  49520. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  49521. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  49522. currentBlendColor.copy( blendColor );
  49523. currentBlendAlpha = blendAlpha;
  49524. }
  49525. currentBlending = blending;
  49526. currentPremultipledAlpha = false;
  49527. }
  49528. function setMaterial( material, frontFaceCW ) {
  49529. material.side === DoubleSide
  49530. ? disable( gl.CULL_FACE )
  49531. : enable( gl.CULL_FACE );
  49532. let flipSided = ( material.side === BackSide );
  49533. if ( frontFaceCW ) flipSided = ! flipSided;
  49534. setFlipSided( flipSided );
  49535. ( material.blending === NormalBlending && material.transparent === false )
  49536. ? setBlending( NoBlending )
  49537. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  49538. depthBuffer.setFunc( material.depthFunc );
  49539. depthBuffer.setTest( material.depthTest );
  49540. depthBuffer.setMask( material.depthWrite );
  49541. colorBuffer.setMask( material.colorWrite );
  49542. const stencilWrite = material.stencilWrite;
  49543. stencilBuffer.setTest( stencilWrite );
  49544. if ( stencilWrite ) {
  49545. stencilBuffer.setMask( material.stencilWriteMask );
  49546. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  49547. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  49548. }
  49549. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  49550. material.alphaToCoverage === true
  49551. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  49552. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49553. }
  49554. //
  49555. function setFlipSided( flipSided ) {
  49556. if ( currentFlipSided !== flipSided ) {
  49557. if ( flipSided ) {
  49558. gl.frontFace( gl.CW );
  49559. } else {
  49560. gl.frontFace( gl.CCW );
  49561. }
  49562. currentFlipSided = flipSided;
  49563. }
  49564. }
  49565. function setCullFace( cullFace ) {
  49566. if ( cullFace !== CullFaceNone ) {
  49567. enable( gl.CULL_FACE );
  49568. if ( cullFace !== currentCullFace ) {
  49569. if ( cullFace === CullFaceBack ) {
  49570. gl.cullFace( gl.BACK );
  49571. } else if ( cullFace === CullFaceFront ) {
  49572. gl.cullFace( gl.FRONT );
  49573. } else {
  49574. gl.cullFace( gl.FRONT_AND_BACK );
  49575. }
  49576. }
  49577. } else {
  49578. disable( gl.CULL_FACE );
  49579. }
  49580. currentCullFace = cullFace;
  49581. }
  49582. function setLineWidth( width ) {
  49583. if ( width !== currentLineWidth ) {
  49584. if ( lineWidthAvailable ) gl.lineWidth( width );
  49585. currentLineWidth = width;
  49586. }
  49587. }
  49588. function setPolygonOffset( polygonOffset, factor, units ) {
  49589. if ( polygonOffset ) {
  49590. enable( gl.POLYGON_OFFSET_FILL );
  49591. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  49592. gl.polygonOffset( factor, units );
  49593. currentPolygonOffsetFactor = factor;
  49594. currentPolygonOffsetUnits = units;
  49595. }
  49596. } else {
  49597. disable( gl.POLYGON_OFFSET_FILL );
  49598. }
  49599. }
  49600. function setScissorTest( scissorTest ) {
  49601. if ( scissorTest ) {
  49602. enable( gl.SCISSOR_TEST );
  49603. } else {
  49604. disable( gl.SCISSOR_TEST );
  49605. }
  49606. }
  49607. // texture
  49608. function activeTexture( webglSlot ) {
  49609. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49610. if ( currentTextureSlot !== webglSlot ) {
  49611. gl.activeTexture( webglSlot );
  49612. currentTextureSlot = webglSlot;
  49613. }
  49614. }
  49615. function bindTexture( webglType, webglTexture, webglSlot ) {
  49616. if ( webglSlot === undefined ) {
  49617. if ( currentTextureSlot === null ) {
  49618. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49619. } else {
  49620. webglSlot = currentTextureSlot;
  49621. }
  49622. }
  49623. let boundTexture = currentBoundTextures[ webglSlot ];
  49624. if ( boundTexture === undefined ) {
  49625. boundTexture = { type: undefined, texture: undefined };
  49626. currentBoundTextures[ webglSlot ] = boundTexture;
  49627. }
  49628. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49629. if ( currentTextureSlot !== webglSlot ) {
  49630. gl.activeTexture( webglSlot );
  49631. currentTextureSlot = webglSlot;
  49632. }
  49633. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49634. boundTexture.type = webglType;
  49635. boundTexture.texture = webglTexture;
  49636. }
  49637. }
  49638. function unbindTexture() {
  49639. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49640. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49641. gl.bindTexture( boundTexture.type, null );
  49642. boundTexture.type = undefined;
  49643. boundTexture.texture = undefined;
  49644. }
  49645. }
  49646. function compressedTexImage2D() {
  49647. try {
  49648. gl.compressedTexImage2D( ...arguments );
  49649. } catch ( e ) {
  49650. error( 'WebGLState:', e );
  49651. }
  49652. }
  49653. function compressedTexImage3D() {
  49654. try {
  49655. gl.compressedTexImage3D( ...arguments );
  49656. } catch ( e ) {
  49657. error( 'WebGLState:', e );
  49658. }
  49659. }
  49660. function texSubImage2D() {
  49661. try {
  49662. gl.texSubImage2D( ...arguments );
  49663. } catch ( e ) {
  49664. error( 'WebGLState:', e );
  49665. }
  49666. }
  49667. function texSubImage3D() {
  49668. try {
  49669. gl.texSubImage3D( ...arguments );
  49670. } catch ( e ) {
  49671. error( 'WebGLState:', e );
  49672. }
  49673. }
  49674. function compressedTexSubImage2D() {
  49675. try {
  49676. gl.compressedTexSubImage2D( ...arguments );
  49677. } catch ( e ) {
  49678. error( 'WebGLState:', e );
  49679. }
  49680. }
  49681. function compressedTexSubImage3D() {
  49682. try {
  49683. gl.compressedTexSubImage3D( ...arguments );
  49684. } catch ( e ) {
  49685. error( 'WebGLState:', e );
  49686. }
  49687. }
  49688. function texStorage2D() {
  49689. try {
  49690. gl.texStorage2D( ...arguments );
  49691. } catch ( e ) {
  49692. error( 'WebGLState:', e );
  49693. }
  49694. }
  49695. function texStorage3D() {
  49696. try {
  49697. gl.texStorage3D( ...arguments );
  49698. } catch ( e ) {
  49699. error( 'WebGLState:', e );
  49700. }
  49701. }
  49702. function texImage2D() {
  49703. try {
  49704. gl.texImage2D( ...arguments );
  49705. } catch ( e ) {
  49706. error( 'WebGLState:', e );
  49707. }
  49708. }
  49709. function texImage3D() {
  49710. try {
  49711. gl.texImage3D( ...arguments );
  49712. } catch ( e ) {
  49713. error( 'WebGLState:', e );
  49714. }
  49715. }
  49716. //
  49717. function scissor( scissor ) {
  49718. if ( currentScissor.equals( scissor ) === false ) {
  49719. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49720. currentScissor.copy( scissor );
  49721. }
  49722. }
  49723. function viewport( viewport ) {
  49724. if ( currentViewport.equals( viewport ) === false ) {
  49725. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49726. currentViewport.copy( viewport );
  49727. }
  49728. }
  49729. function updateUBOMapping( uniformsGroup, program ) {
  49730. let mapping = uboProgramMap.get( program );
  49731. if ( mapping === undefined ) {
  49732. mapping = new WeakMap();
  49733. uboProgramMap.set( program, mapping );
  49734. }
  49735. let blockIndex = mapping.get( uniformsGroup );
  49736. if ( blockIndex === undefined ) {
  49737. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49738. mapping.set( uniformsGroup, blockIndex );
  49739. }
  49740. }
  49741. function uniformBlockBinding( uniformsGroup, program ) {
  49742. const mapping = uboProgramMap.get( program );
  49743. const blockIndex = mapping.get( uniformsGroup );
  49744. if ( uboBindings.get( program ) !== blockIndex ) {
  49745. // bind shader specific block index to global block point
  49746. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49747. uboBindings.set( program, blockIndex );
  49748. }
  49749. }
  49750. //
  49751. function reset() {
  49752. // reset state
  49753. gl.disable( gl.BLEND );
  49754. gl.disable( gl.CULL_FACE );
  49755. gl.disable( gl.DEPTH_TEST );
  49756. gl.disable( gl.POLYGON_OFFSET_FILL );
  49757. gl.disable( gl.SCISSOR_TEST );
  49758. gl.disable( gl.STENCIL_TEST );
  49759. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49760. gl.blendEquation( gl.FUNC_ADD );
  49761. gl.blendFunc( gl.ONE, gl.ZERO );
  49762. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49763. gl.blendColor( 0, 0, 0, 0 );
  49764. gl.colorMask( true, true, true, true );
  49765. gl.clearColor( 0, 0, 0, 0 );
  49766. gl.depthMask( true );
  49767. gl.depthFunc( gl.LESS );
  49768. depthBuffer.setReversed( false );
  49769. gl.clearDepth( 1 );
  49770. gl.stencilMask( 0xffffffff );
  49771. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49772. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49773. gl.clearStencil( 0 );
  49774. gl.cullFace( gl.BACK );
  49775. gl.frontFace( gl.CCW );
  49776. gl.polygonOffset( 0, 0 );
  49777. gl.activeTexture( gl.TEXTURE0 );
  49778. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49779. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49780. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49781. gl.useProgram( null );
  49782. gl.lineWidth( 1 );
  49783. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49784. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49785. // reset internals
  49786. enabledCapabilities = {};
  49787. currentTextureSlot = null;
  49788. currentBoundTextures = {};
  49789. currentBoundFramebuffers = {};
  49790. currentDrawbuffers = new WeakMap();
  49791. defaultDrawbuffers = [];
  49792. currentProgram = null;
  49793. currentBlendingEnabled = false;
  49794. currentBlending = null;
  49795. currentBlendEquation = null;
  49796. currentBlendSrc = null;
  49797. currentBlendDst = null;
  49798. currentBlendEquationAlpha = null;
  49799. currentBlendSrcAlpha = null;
  49800. currentBlendDstAlpha = null;
  49801. currentBlendColor = new Color( 0, 0, 0 );
  49802. currentBlendAlpha = 0;
  49803. currentPremultipledAlpha = false;
  49804. currentFlipSided = null;
  49805. currentCullFace = null;
  49806. currentLineWidth = null;
  49807. currentPolygonOffsetFactor = null;
  49808. currentPolygonOffsetUnits = null;
  49809. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49810. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49811. colorBuffer.reset();
  49812. depthBuffer.reset();
  49813. stencilBuffer.reset();
  49814. }
  49815. return {
  49816. buffers: {
  49817. color: colorBuffer,
  49818. depth: depthBuffer,
  49819. stencil: stencilBuffer
  49820. },
  49821. enable: enable,
  49822. disable: disable,
  49823. bindFramebuffer: bindFramebuffer,
  49824. drawBuffers: drawBuffers,
  49825. useProgram: useProgram,
  49826. setBlending: setBlending,
  49827. setMaterial: setMaterial,
  49828. setFlipSided: setFlipSided,
  49829. setCullFace: setCullFace,
  49830. setLineWidth: setLineWidth,
  49831. setPolygonOffset: setPolygonOffset,
  49832. setScissorTest: setScissorTest,
  49833. activeTexture: activeTexture,
  49834. bindTexture: bindTexture,
  49835. unbindTexture: unbindTexture,
  49836. compressedTexImage2D: compressedTexImage2D,
  49837. compressedTexImage3D: compressedTexImage3D,
  49838. texImage2D: texImage2D,
  49839. texImage3D: texImage3D,
  49840. updateUBOMapping: updateUBOMapping,
  49841. uniformBlockBinding: uniformBlockBinding,
  49842. texStorage2D: texStorage2D,
  49843. texStorage3D: texStorage3D,
  49844. texSubImage2D: texSubImage2D,
  49845. texSubImage3D: texSubImage3D,
  49846. compressedTexSubImage2D: compressedTexSubImage2D,
  49847. compressedTexSubImage3D: compressedTexSubImage3D,
  49848. scissor: scissor,
  49849. viewport: viewport,
  49850. reset: reset
  49851. };
  49852. }
  49853. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49854. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49855. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49856. const _imageDimensions = new Vector2();
  49857. const _videoTextures = new WeakMap();
  49858. let _canvas;
  49859. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49860. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49861. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49862. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49863. let useOffscreenCanvas = false;
  49864. try {
  49865. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49866. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49867. } catch ( err ) {
  49868. // Ignore any errors
  49869. }
  49870. function createCanvas( width, height ) {
  49871. // Use OffscreenCanvas when available. Specially needed in web workers
  49872. return useOffscreenCanvas ?
  49873. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49874. }
  49875. function resizeImage( image, needsNewCanvas, maxSize ) {
  49876. let scale = 1;
  49877. const dimensions = getDimensions( image );
  49878. // handle case if texture exceeds max size
  49879. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49880. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49881. }
  49882. // only perform resize if necessary
  49883. if ( scale < 1 ) {
  49884. // only perform resize for certain image types
  49885. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49886. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49887. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49888. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49889. const width = Math.floor( scale * dimensions.width );
  49890. const height = Math.floor( scale * dimensions.height );
  49891. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49892. // cube textures can't reuse the same canvas
  49893. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49894. canvas.width = width;
  49895. canvas.height = height;
  49896. const context = canvas.getContext( '2d' );
  49897. context.drawImage( image, 0, 0, width, height );
  49898. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49899. return canvas;
  49900. } else {
  49901. if ( 'data' in image ) {
  49902. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49903. }
  49904. return image;
  49905. }
  49906. }
  49907. return image;
  49908. }
  49909. function textureNeedsGenerateMipmaps( texture ) {
  49910. return texture.generateMipmaps;
  49911. }
  49912. function generateMipmap( target ) {
  49913. _gl.generateMipmap( target );
  49914. }
  49915. function getTargetType( texture ) {
  49916. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49917. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49918. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49919. return _gl.TEXTURE_2D;
  49920. }
  49921. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49922. if ( internalFormatName !== null ) {
  49923. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49924. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49925. }
  49926. let internalFormat = glFormat;
  49927. if ( glFormat === _gl.RED ) {
  49928. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49929. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49930. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49931. }
  49932. if ( glFormat === _gl.RED_INTEGER ) {
  49933. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49934. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  49935. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  49936. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  49937. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  49938. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  49939. }
  49940. if ( glFormat === _gl.RG ) {
  49941. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  49942. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  49943. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  49944. }
  49945. if ( glFormat === _gl.RG_INTEGER ) {
  49946. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  49947. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  49948. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  49949. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  49950. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  49951. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  49952. }
  49953. if ( glFormat === _gl.RGB_INTEGER ) {
  49954. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  49955. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  49956. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  49957. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  49958. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  49959. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  49960. }
  49961. if ( glFormat === _gl.RGBA_INTEGER ) {
  49962. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  49963. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  49964. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  49965. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  49966. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  49967. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  49968. }
  49969. if ( glFormat === _gl.RGB ) {
  49970. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  49971. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  49972. }
  49973. if ( glFormat === _gl.RGBA ) {
  49974. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49975. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  49976. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  49977. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  49978. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  49979. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  49980. }
  49981. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  49982. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  49983. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  49984. extensions.get( 'EXT_color_buffer_float' );
  49985. }
  49986. return internalFormat;
  49987. }
  49988. function getInternalDepthFormat( useStencil, depthType ) {
  49989. let glInternalFormat;
  49990. if ( useStencil ) {
  49991. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49992. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49993. } else if ( depthType === FloatType ) {
  49994. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  49995. } else if ( depthType === UnsignedShortType ) {
  49996. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49997. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49998. }
  49999. } else {
  50000. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  50001. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50002. } else if ( depthType === FloatType ) {
  50003. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  50004. } else if ( depthType === UnsignedShortType ) {
  50005. glInternalFormat = _gl.DEPTH_COMPONENT16;
  50006. }
  50007. }
  50008. return glInternalFormat;
  50009. }
  50010. function getMipLevels( texture, image ) {
  50011. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  50012. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  50013. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  50014. // user-defined mipmaps
  50015. return texture.mipmaps.length;
  50016. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  50017. return image.mipmaps.length;
  50018. } else {
  50019. // texture without mipmaps (only base level)
  50020. return 1;
  50021. }
  50022. }
  50023. //
  50024. function onTextureDispose( event ) {
  50025. const texture = event.target;
  50026. texture.removeEventListener( 'dispose', onTextureDispose );
  50027. deallocateTexture( texture );
  50028. if ( texture.isVideoTexture ) {
  50029. _videoTextures.delete( texture );
  50030. }
  50031. }
  50032. function onRenderTargetDispose( event ) {
  50033. const renderTarget = event.target;
  50034. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  50035. deallocateRenderTarget( renderTarget );
  50036. }
  50037. //
  50038. function deallocateTexture( texture ) {
  50039. const textureProperties = properties.get( texture );
  50040. if ( textureProperties.__webglInit === undefined ) return;
  50041. // check if it's necessary to remove the WebGLTexture object
  50042. const source = texture.source;
  50043. const webglTextures = _sources.get( source );
  50044. if ( webglTextures ) {
  50045. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  50046. webglTexture.usedTimes --;
  50047. // the WebGLTexture object is not used anymore, remove it
  50048. if ( webglTexture.usedTimes === 0 ) {
  50049. deleteTexture( texture );
  50050. }
  50051. // remove the weak map entry if no WebGLTexture uses the source anymore
  50052. if ( Object.keys( webglTextures ).length === 0 ) {
  50053. _sources.delete( source );
  50054. }
  50055. }
  50056. properties.remove( texture );
  50057. }
  50058. function deleteTexture( texture ) {
  50059. const textureProperties = properties.get( texture );
  50060. _gl.deleteTexture( textureProperties.__webglTexture );
  50061. const source = texture.source;
  50062. const webglTextures = _sources.get( source );
  50063. delete webglTextures[ textureProperties.__cacheKey ];
  50064. info.memory.textures --;
  50065. }
  50066. function deallocateRenderTarget( renderTarget ) {
  50067. const renderTargetProperties = properties.get( renderTarget );
  50068. if ( renderTarget.depthTexture ) {
  50069. renderTarget.depthTexture.dispose();
  50070. properties.remove( renderTarget.depthTexture );
  50071. }
  50072. if ( renderTarget.isWebGLCubeRenderTarget ) {
  50073. for ( let i = 0; i < 6; i ++ ) {
  50074. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  50075. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  50076. } else {
  50077. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  50078. }
  50079. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  50080. }
  50081. } else {
  50082. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  50083. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  50084. } else {
  50085. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  50086. }
  50087. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  50088. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  50089. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  50090. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  50091. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50092. }
  50093. }
  50094. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  50095. }
  50096. const textures = renderTarget.textures;
  50097. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50098. const attachmentProperties = properties.get( textures[ i ] );
  50099. if ( attachmentProperties.__webglTexture ) {
  50100. _gl.deleteTexture( attachmentProperties.__webglTexture );
  50101. info.memory.textures --;
  50102. }
  50103. properties.remove( textures[ i ] );
  50104. }
  50105. properties.remove( renderTarget );
  50106. }
  50107. //
  50108. let textureUnits = 0;
  50109. function resetTextureUnits() {
  50110. textureUnits = 0;
  50111. }
  50112. function allocateTextureUnit() {
  50113. const textureUnit = textureUnits;
  50114. if ( textureUnit >= capabilities.maxTextures ) {
  50115. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  50116. }
  50117. textureUnits += 1;
  50118. return textureUnit;
  50119. }
  50120. function getTextureCacheKey( texture ) {
  50121. const array = [];
  50122. array.push( texture.wrapS );
  50123. array.push( texture.wrapT );
  50124. array.push( texture.wrapR || 0 );
  50125. array.push( texture.magFilter );
  50126. array.push( texture.minFilter );
  50127. array.push( texture.anisotropy );
  50128. array.push( texture.internalFormat );
  50129. array.push( texture.format );
  50130. array.push( texture.type );
  50131. array.push( texture.generateMipmaps );
  50132. array.push( texture.premultiplyAlpha );
  50133. array.push( texture.flipY );
  50134. array.push( texture.unpackAlignment );
  50135. array.push( texture.colorSpace );
  50136. return array.join();
  50137. }
  50138. //
  50139. function setTexture2D( texture, slot ) {
  50140. const textureProperties = properties.get( texture );
  50141. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  50142. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50143. const image = texture.image;
  50144. if ( image === null ) {
  50145. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  50146. } else if ( image.complete === false ) {
  50147. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  50148. } else {
  50149. uploadTexture( textureProperties, texture, slot );
  50150. return;
  50151. }
  50152. } else if ( texture.isExternalTexture ) {
  50153. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  50154. }
  50155. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50156. }
  50157. function setTexture2DArray( texture, slot ) {
  50158. const textureProperties = properties.get( texture );
  50159. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50160. uploadTexture( textureProperties, texture, slot );
  50161. return;
  50162. } else if ( texture.isExternalTexture ) {
  50163. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  50164. }
  50165. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50166. }
  50167. function setTexture3D( texture, slot ) {
  50168. const textureProperties = properties.get( texture );
  50169. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50170. uploadTexture( textureProperties, texture, slot );
  50171. return;
  50172. }
  50173. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50174. }
  50175. function setTextureCube( texture, slot ) {
  50176. const textureProperties = properties.get( texture );
  50177. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50178. uploadCubeTexture( textureProperties, texture, slot );
  50179. return;
  50180. }
  50181. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50182. }
  50183. const wrappingToGL = {
  50184. [ RepeatWrapping ]: _gl.REPEAT,
  50185. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  50186. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  50187. };
  50188. const filterToGL = {
  50189. [ NearestFilter ]: _gl.NEAREST,
  50190. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  50191. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  50192. [ LinearFilter ]: _gl.LINEAR,
  50193. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  50194. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  50195. };
  50196. const compareToGL = {
  50197. [ NeverCompare ]: _gl.NEVER,
  50198. [ AlwaysCompare ]: _gl.ALWAYS,
  50199. [ LessCompare ]: _gl.LESS,
  50200. [ LessEqualCompare ]: _gl.LEQUAL,
  50201. [ EqualCompare ]: _gl.EQUAL,
  50202. [ GreaterEqualCompare ]: _gl.GEQUAL,
  50203. [ GreaterCompare ]: _gl.GREATER,
  50204. [ NotEqualCompare ]: _gl.NOTEQUAL
  50205. };
  50206. function setTextureParameters( textureType, texture ) {
  50207. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  50208. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  50209. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  50210. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  50211. }
  50212. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  50213. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  50214. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  50215. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  50216. }
  50217. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  50218. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  50219. if ( texture.compareFunction ) {
  50220. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  50221. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  50222. }
  50223. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  50224. if ( texture.magFilter === NearestFilter ) return;
  50225. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  50226. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  50227. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  50228. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  50229. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  50230. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  50231. }
  50232. }
  50233. }
  50234. function initTexture( textureProperties, texture ) {
  50235. let forceUpload = false;
  50236. if ( textureProperties.__webglInit === undefined ) {
  50237. textureProperties.__webglInit = true;
  50238. texture.addEventListener( 'dispose', onTextureDispose );
  50239. }
  50240. // create Source <-> WebGLTextures mapping if necessary
  50241. const source = texture.source;
  50242. let webglTextures = _sources.get( source );
  50243. if ( webglTextures === undefined ) {
  50244. webglTextures = {};
  50245. _sources.set( source, webglTextures );
  50246. }
  50247. // check if there is already a WebGLTexture object for the given texture parameters
  50248. const textureCacheKey = getTextureCacheKey( texture );
  50249. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  50250. // if not, create a new instance of WebGLTexture
  50251. if ( webglTextures[ textureCacheKey ] === undefined ) {
  50252. // create new entry
  50253. webglTextures[ textureCacheKey ] = {
  50254. texture: _gl.createTexture(),
  50255. usedTimes: 0
  50256. };
  50257. info.memory.textures ++;
  50258. // when a new instance of WebGLTexture was created, a texture upload is required
  50259. // even if the image contents are identical
  50260. forceUpload = true;
  50261. }
  50262. webglTextures[ textureCacheKey ].usedTimes ++;
  50263. // every time the texture cache key changes, it's necessary to check if an instance of
  50264. // WebGLTexture can be deleted in order to avoid a memory leak.
  50265. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  50266. if ( webglTexture !== undefined ) {
  50267. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  50268. if ( webglTexture.usedTimes === 0 ) {
  50269. deleteTexture( texture );
  50270. }
  50271. }
  50272. // store references to cache key and WebGLTexture object
  50273. textureProperties.__cacheKey = textureCacheKey;
  50274. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  50275. }
  50276. return forceUpload;
  50277. }
  50278. function getRow( index, rowLength, componentStride ) {
  50279. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  50280. }
  50281. function updateTexture( texture, image, glFormat, glType ) {
  50282. const componentStride = 4; // only RGBA supported
  50283. const updateRanges = texture.updateRanges;
  50284. if ( updateRanges.length === 0 ) {
  50285. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  50286. } else {
  50287. // Before applying update ranges, we merge any adjacent / overlapping
  50288. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  50289. // to performance improvements for applications which make heavy use of
  50290. // update ranges. Likely due to GPU command overhead.
  50291. //
  50292. // Note that to reduce garbage collection between frames, we merge the
  50293. // update ranges in-place. This is safe because this method will clear the
  50294. // update ranges once updated.
  50295. updateRanges.sort( ( a, b ) => a.start - b.start );
  50296. // To merge the update ranges in-place, we work from left to right in the
  50297. // existing updateRanges array, merging ranges. This may result in a final
  50298. // array which is smaller than the original. This index tracks the last
  50299. // index representing a merged range, any data after this index can be
  50300. // trimmed once the merge algorithm is completed.
  50301. let mergeIndex = 0;
  50302. for ( let i = 1; i < updateRanges.length; i ++ ) {
  50303. const previousRange = updateRanges[ mergeIndex ];
  50304. const range = updateRanges[ i ];
  50305. // Only merge if in the same row and overlapping/adjacent
  50306. const previousEnd = previousRange.start + previousRange.count;
  50307. const currentRow = getRow( range.start, image.width, componentStride );
  50308. const previousRow = getRow( previousRange.start, image.width, componentStride );
  50309. // We add one here to merge adjacent ranges. This is safe because ranges
  50310. // operate over positive integers.
  50311. if (
  50312. range.start <= previousEnd + 1 &&
  50313. currentRow === previousRow &&
  50314. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  50315. ) {
  50316. previousRange.count = Math.max(
  50317. previousRange.count,
  50318. range.start + range.count - previousRange.start
  50319. );
  50320. } else {
  50321. ++ mergeIndex;
  50322. updateRanges[ mergeIndex ] = range;
  50323. }
  50324. }
  50325. // Trim the array to only contain the merged ranges.
  50326. updateRanges.length = mergeIndex + 1;
  50327. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  50328. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  50329. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  50330. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  50331. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50332. const range = updateRanges[ i ];
  50333. const pixelStart = Math.floor( range.start / componentStride );
  50334. const pixelCount = Math.ceil( range.count / componentStride );
  50335. const x = pixelStart % image.width;
  50336. const y = Math.floor( pixelStart / image.width );
  50337. // Assumes update ranges refer to contiguous memory
  50338. const width = pixelCount;
  50339. const height = 1;
  50340. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  50341. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  50342. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  50343. }
  50344. texture.clearUpdateRanges();
  50345. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  50346. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  50347. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  50348. }
  50349. }
  50350. function uploadTexture( textureProperties, texture, slot ) {
  50351. let textureType = _gl.TEXTURE_2D;
  50352. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  50353. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  50354. const forceUpload = initTexture( textureProperties, texture );
  50355. const source = texture.source;
  50356. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50357. const sourceProperties = properties.get( source );
  50358. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50359. state.activeTexture( _gl.TEXTURE0 + slot );
  50360. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50361. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50362. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50363. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50364. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50365. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50366. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50367. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  50368. image = verifyColorSpace( texture, image );
  50369. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50370. const glType = utils.convert( texture.type );
  50371. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  50372. setTextureParameters( textureType, texture );
  50373. let mipmap;
  50374. const mipmaps = texture.mipmaps;
  50375. const useTexStorage = ( texture.isVideoTexture !== true );
  50376. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50377. const dataReady = source.dataReady;
  50378. const levels = getMipLevels( texture, image );
  50379. if ( texture.isDepthTexture ) {
  50380. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  50381. //
  50382. if ( allocateMemory ) {
  50383. if ( useTexStorage ) {
  50384. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  50385. } else {
  50386. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  50387. }
  50388. }
  50389. } else if ( texture.isDataTexture ) {
  50390. // use manually created mipmaps if available
  50391. // if there are no manual mipmaps
  50392. // set 0 level mipmap and then use GL to generate other mipmap levels
  50393. if ( mipmaps.length > 0 ) {
  50394. if ( useTexStorage && allocateMemory ) {
  50395. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50396. }
  50397. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50398. mipmap = mipmaps[ i ];
  50399. if ( useTexStorage ) {
  50400. if ( dataReady ) {
  50401. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50402. }
  50403. } else {
  50404. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50405. }
  50406. }
  50407. texture.generateMipmaps = false;
  50408. } else {
  50409. if ( useTexStorage ) {
  50410. if ( allocateMemory ) {
  50411. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50412. }
  50413. if ( dataReady ) {
  50414. updateTexture( texture, image, glFormat, glType );
  50415. }
  50416. } else {
  50417. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  50418. }
  50419. }
  50420. } else if ( texture.isCompressedTexture ) {
  50421. if ( texture.isCompressedArrayTexture ) {
  50422. if ( useTexStorage && allocateMemory ) {
  50423. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  50424. }
  50425. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50426. mipmap = mipmaps[ i ];
  50427. if ( texture.format !== RGBAFormat ) {
  50428. if ( glFormat !== null ) {
  50429. if ( useTexStorage ) {
  50430. if ( dataReady ) {
  50431. if ( texture.layerUpdates.size > 0 ) {
  50432. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  50433. for ( const layerIndex of texture.layerUpdates ) {
  50434. const layerData = mipmap.data.subarray(
  50435. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  50436. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  50437. );
  50438. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  50439. }
  50440. texture.clearLayerUpdates();
  50441. } else {
  50442. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  50443. }
  50444. }
  50445. } else {
  50446. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  50447. }
  50448. } else {
  50449. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50450. }
  50451. } else {
  50452. if ( useTexStorage ) {
  50453. if ( dataReady ) {
  50454. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  50455. }
  50456. } else {
  50457. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  50458. }
  50459. }
  50460. }
  50461. } else {
  50462. if ( useTexStorage && allocateMemory ) {
  50463. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50464. }
  50465. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50466. mipmap = mipmaps[ i ];
  50467. if ( texture.format !== RGBAFormat ) {
  50468. if ( glFormat !== null ) {
  50469. if ( useTexStorage ) {
  50470. if ( dataReady ) {
  50471. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50472. }
  50473. } else {
  50474. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50475. }
  50476. } else {
  50477. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50478. }
  50479. } else {
  50480. if ( useTexStorage ) {
  50481. if ( dataReady ) {
  50482. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50483. }
  50484. } else {
  50485. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50486. }
  50487. }
  50488. }
  50489. }
  50490. } else if ( texture.isDataArrayTexture ) {
  50491. if ( useTexStorage ) {
  50492. if ( allocateMemory ) {
  50493. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  50494. }
  50495. if ( dataReady ) {
  50496. if ( texture.layerUpdates.size > 0 ) {
  50497. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  50498. for ( const layerIndex of texture.layerUpdates ) {
  50499. const layerData = image.data.subarray(
  50500. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  50501. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  50502. );
  50503. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  50504. }
  50505. texture.clearLayerUpdates();
  50506. } else {
  50507. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50508. }
  50509. }
  50510. } else {
  50511. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50512. }
  50513. } else if ( texture.isData3DTexture ) {
  50514. if ( useTexStorage ) {
  50515. if ( allocateMemory ) {
  50516. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  50517. }
  50518. if ( dataReady ) {
  50519. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50520. }
  50521. } else {
  50522. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50523. }
  50524. } else if ( texture.isFramebufferTexture ) {
  50525. if ( allocateMemory ) {
  50526. if ( useTexStorage ) {
  50527. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50528. } else {
  50529. let width = image.width, height = image.height;
  50530. for ( let i = 0; i < levels; i ++ ) {
  50531. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  50532. width >>= 1;
  50533. height >>= 1;
  50534. }
  50535. }
  50536. }
  50537. } else {
  50538. // regular Texture (image, video, canvas)
  50539. // use manually created mipmaps if available
  50540. // if there are no manual mipmaps
  50541. // set 0 level mipmap and then use GL to generate other mipmap levels
  50542. if ( mipmaps.length > 0 ) {
  50543. if ( useTexStorage && allocateMemory ) {
  50544. const dimensions = getDimensions( mipmaps[ 0 ] );
  50545. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50546. }
  50547. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50548. mipmap = mipmaps[ i ];
  50549. if ( useTexStorage ) {
  50550. if ( dataReady ) {
  50551. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  50552. }
  50553. } else {
  50554. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  50555. }
  50556. }
  50557. texture.generateMipmaps = false;
  50558. } else {
  50559. if ( useTexStorage ) {
  50560. if ( allocateMemory ) {
  50561. const dimensions = getDimensions( image );
  50562. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50563. }
  50564. if ( dataReady ) {
  50565. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  50566. }
  50567. } else {
  50568. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  50569. }
  50570. }
  50571. }
  50572. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50573. generateMipmap( textureType );
  50574. }
  50575. sourceProperties.__version = source.version;
  50576. if ( texture.onUpdate ) texture.onUpdate( texture );
  50577. }
  50578. textureProperties.__version = texture.version;
  50579. }
  50580. function uploadCubeTexture( textureProperties, texture, slot ) {
  50581. if ( texture.image.length !== 6 ) return;
  50582. const forceUpload = initTexture( textureProperties, texture );
  50583. const source = texture.source;
  50584. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50585. const sourceProperties = properties.get( source );
  50586. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50587. state.activeTexture( _gl.TEXTURE0 + slot );
  50588. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50589. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50590. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50591. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50592. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50593. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50594. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50595. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  50596. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  50597. const cubeImage = [];
  50598. for ( let i = 0; i < 6; i ++ ) {
  50599. if ( ! isCompressed && ! isDataTexture ) {
  50600. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50601. } else {
  50602. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50603. }
  50604. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50605. }
  50606. const image = cubeImage[ 0 ],
  50607. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50608. glType = utils.convert( texture.type ),
  50609. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50610. const useTexStorage = ( texture.isVideoTexture !== true );
  50611. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50612. const dataReady = source.dataReady;
  50613. let levels = getMipLevels( texture, image );
  50614. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50615. let mipmaps;
  50616. if ( isCompressed ) {
  50617. if ( useTexStorage && allocateMemory ) {
  50618. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50619. }
  50620. for ( let i = 0; i < 6; i ++ ) {
  50621. mipmaps = cubeImage[ i ].mipmaps;
  50622. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50623. const mipmap = mipmaps[ j ];
  50624. if ( texture.format !== RGBAFormat ) {
  50625. if ( glFormat !== null ) {
  50626. if ( useTexStorage ) {
  50627. if ( dataReady ) {
  50628. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50629. }
  50630. } else {
  50631. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50632. }
  50633. } else {
  50634. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50635. }
  50636. } else {
  50637. if ( useTexStorage ) {
  50638. if ( dataReady ) {
  50639. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50640. }
  50641. } else {
  50642. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50643. }
  50644. }
  50645. }
  50646. }
  50647. } else {
  50648. mipmaps = texture.mipmaps;
  50649. if ( useTexStorage && allocateMemory ) {
  50650. // TODO: Uniformly handle mipmap definitions
  50651. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50652. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50653. if ( mipmaps.length > 0 ) levels ++;
  50654. const dimensions = getDimensions( cubeImage[ 0 ] );
  50655. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50656. }
  50657. for ( let i = 0; i < 6; i ++ ) {
  50658. if ( isDataTexture ) {
  50659. if ( useTexStorage ) {
  50660. if ( dataReady ) {
  50661. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50662. }
  50663. } else {
  50664. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50665. }
  50666. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50667. const mipmap = mipmaps[ j ];
  50668. const mipmapImage = mipmap.image[ i ].image;
  50669. if ( useTexStorage ) {
  50670. if ( dataReady ) {
  50671. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50672. }
  50673. } else {
  50674. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50675. }
  50676. }
  50677. } else {
  50678. if ( useTexStorage ) {
  50679. if ( dataReady ) {
  50680. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50681. }
  50682. } else {
  50683. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50684. }
  50685. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50686. const mipmap = mipmaps[ j ];
  50687. if ( useTexStorage ) {
  50688. if ( dataReady ) {
  50689. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50690. }
  50691. } else {
  50692. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50693. }
  50694. }
  50695. }
  50696. }
  50697. }
  50698. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50699. // We assume images for cube map have the same size.
  50700. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50701. }
  50702. sourceProperties.__version = source.version;
  50703. if ( texture.onUpdate ) texture.onUpdate( texture );
  50704. }
  50705. textureProperties.__version = texture.version;
  50706. }
  50707. // Render targets
  50708. // Setup storage for target texture and bind it to correct framebuffer
  50709. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50710. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50711. const glType = utils.convert( texture.type );
  50712. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50713. const renderTargetProperties = properties.get( renderTarget );
  50714. const textureProperties = properties.get( texture );
  50715. textureProperties.__renderTarget = renderTarget;
  50716. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50717. const width = Math.max( 1, renderTarget.width >> level );
  50718. const height = Math.max( 1, renderTarget.height >> level );
  50719. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50720. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50721. } else {
  50722. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50723. }
  50724. }
  50725. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50726. if ( useMultisampledRTT( renderTarget ) ) {
  50727. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50728. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50729. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50730. }
  50731. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50732. }
  50733. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50734. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  50735. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50736. if ( renderTarget.depthBuffer ) {
  50737. // retrieve the depth attachment types
  50738. const depthTexture = renderTarget.depthTexture;
  50739. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50740. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50741. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50742. // set up the attachment
  50743. if ( useMultisampledRTT( renderTarget ) ) {
  50744. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50745. } else if ( useMultisample ) {
  50746. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50747. } else {
  50748. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50749. }
  50750. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50751. } else {
  50752. const textures = renderTarget.textures;
  50753. for ( let i = 0; i < textures.length; i ++ ) {
  50754. const texture = textures[ i ];
  50755. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50756. const glType = utils.convert( texture.type );
  50757. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50758. if ( useMultisampledRTT( renderTarget ) ) {
  50759. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50760. } else if ( useMultisample ) {
  50761. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50762. } else {
  50763. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50764. }
  50765. }
  50766. }
  50767. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50768. }
  50769. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50770. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50771. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50772. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50773. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50774. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50775. }
  50776. const textureProperties = properties.get( renderTarget.depthTexture );
  50777. textureProperties.__renderTarget = renderTarget;
  50778. // upload an empty depth texture with framebuffer size
  50779. if ( ! textureProperties.__webglTexture ||
  50780. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50781. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50782. renderTarget.depthTexture.image.width = renderTarget.width;
  50783. renderTarget.depthTexture.image.height = renderTarget.height;
  50784. renderTarget.depthTexture.needsUpdate = true;
  50785. }
  50786. if ( isCube ) {
  50787. // For cube depth textures, initialize and bind without uploading image data
  50788. if ( textureProperties.__webglInit === undefined ) {
  50789. textureProperties.__webglInit = true;
  50790. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50791. }
  50792. // Only create and allocate storage once
  50793. if ( textureProperties.__webglTexture === undefined ) {
  50794. textureProperties.__webglTexture = _gl.createTexture();
  50795. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50796. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50797. // Allocate storage for all 6 faces with correct depth texture format
  50798. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50799. const glType = utils.convert( renderTarget.depthTexture.type );
  50800. // Use proper internal format for depth textures
  50801. let glInternalFormat;
  50802. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50803. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50804. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50805. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50806. }
  50807. for ( let i = 0; i < 6; i ++ ) {
  50808. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50809. }
  50810. }
  50811. } else {
  50812. setTexture2D( renderTarget.depthTexture, 0 );
  50813. }
  50814. const webglDepthTexture = textureProperties.__webglTexture;
  50815. const samples = getRenderTargetSamples( renderTarget );
  50816. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50817. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50818. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50819. if ( useMultisampledRTT( renderTarget ) ) {
  50820. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50821. } else {
  50822. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50823. }
  50824. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50825. if ( useMultisampledRTT( renderTarget ) ) {
  50826. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50827. } else {
  50828. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50829. }
  50830. } else {
  50831. throw new Error( 'Unknown depthTexture format' );
  50832. }
  50833. }
  50834. // Setup GL resources for a non-texture depth buffer
  50835. function setupDepthRenderbuffer( renderTarget ) {
  50836. const renderTargetProperties = properties.get( renderTarget );
  50837. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50838. // if the bound depth texture has changed
  50839. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50840. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50841. const depthTexture = renderTarget.depthTexture;
  50842. if ( renderTargetProperties.__depthDisposeCallback ) {
  50843. renderTargetProperties.__depthDisposeCallback();
  50844. }
  50845. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50846. if ( depthTexture ) {
  50847. const disposeEvent = () => {
  50848. delete renderTargetProperties.__boundDepthTexture;
  50849. delete renderTargetProperties.__depthDisposeCallback;
  50850. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50851. };
  50852. depthTexture.addEventListener( 'dispose', disposeEvent );
  50853. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50854. }
  50855. renderTargetProperties.__boundDepthTexture = depthTexture;
  50856. }
  50857. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50858. if ( isCube ) {
  50859. // For cube render targets with depth texture, setup each face
  50860. for ( let i = 0; i < 6; i ++ ) {
  50861. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50862. }
  50863. } else {
  50864. const mipmaps = renderTarget.texture.mipmaps;
  50865. if ( mipmaps && mipmaps.length > 0 ) {
  50866. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50867. } else {
  50868. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50869. }
  50870. }
  50871. } else {
  50872. if ( isCube ) {
  50873. renderTargetProperties.__webglDepthbuffer = [];
  50874. for ( let i = 0; i < 6; i ++ ) {
  50875. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50876. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50877. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50878. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50879. } else {
  50880. // attach buffer if it's been created already
  50881. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50882. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50883. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50884. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50885. }
  50886. }
  50887. } else {
  50888. const mipmaps = renderTarget.texture.mipmaps;
  50889. if ( mipmaps && mipmaps.length > 0 ) {
  50890. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50891. } else {
  50892. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50893. }
  50894. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50895. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50896. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50897. } else {
  50898. // attach buffer if it's been created already
  50899. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50900. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50901. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50902. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50903. }
  50904. }
  50905. }
  50906. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50907. }
  50908. // rebind framebuffer with external textures
  50909. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50910. const renderTargetProperties = properties.get( renderTarget );
  50911. if ( colorTexture !== undefined ) {
  50912. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50913. }
  50914. if ( depthTexture !== undefined ) {
  50915. setupDepthRenderbuffer( renderTarget );
  50916. }
  50917. }
  50918. // Set up GL resources for the render target
  50919. function setupRenderTarget( renderTarget ) {
  50920. const texture = renderTarget.texture;
  50921. const renderTargetProperties = properties.get( renderTarget );
  50922. const textureProperties = properties.get( texture );
  50923. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50924. const textures = renderTarget.textures;
  50925. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50926. const isMultipleRenderTargets = ( textures.length > 1 );
  50927. if ( ! isMultipleRenderTargets ) {
  50928. if ( textureProperties.__webglTexture === undefined ) {
  50929. textureProperties.__webglTexture = _gl.createTexture();
  50930. }
  50931. textureProperties.__version = texture.version;
  50932. info.memory.textures ++;
  50933. }
  50934. // Setup framebuffer
  50935. if ( isCube ) {
  50936. renderTargetProperties.__webglFramebuffer = [];
  50937. for ( let i = 0; i < 6; i ++ ) {
  50938. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50939. renderTargetProperties.__webglFramebuffer[ i ] = [];
  50940. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50941. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  50942. }
  50943. } else {
  50944. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  50945. }
  50946. }
  50947. } else {
  50948. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50949. renderTargetProperties.__webglFramebuffer = [];
  50950. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50951. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  50952. }
  50953. } else {
  50954. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  50955. }
  50956. if ( isMultipleRenderTargets ) {
  50957. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50958. const attachmentProperties = properties.get( textures[ i ] );
  50959. if ( attachmentProperties.__webglTexture === undefined ) {
  50960. attachmentProperties.__webglTexture = _gl.createTexture();
  50961. info.memory.textures ++;
  50962. }
  50963. }
  50964. }
  50965. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  50966. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  50967. renderTargetProperties.__webglColorRenderbuffer = [];
  50968. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50969. for ( let i = 0; i < textures.length; i ++ ) {
  50970. const texture = textures[ i ];
  50971. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  50972. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50973. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50974. const glType = utils.convert( texture.type );
  50975. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  50976. const samples = getRenderTargetSamples( renderTarget );
  50977. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50978. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50979. }
  50980. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50981. if ( renderTarget.depthBuffer ) {
  50982. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  50983. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  50984. }
  50985. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50986. }
  50987. }
  50988. // Setup color buffer
  50989. if ( isCube ) {
  50990. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50991. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50992. for ( let i = 0; i < 6; i ++ ) {
  50993. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50994. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50995. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  50996. }
  50997. } else {
  50998. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  50999. }
  51000. }
  51001. if ( textureNeedsGenerateMipmaps( texture ) ) {
  51002. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  51003. }
  51004. state.unbindTexture();
  51005. } else if ( isMultipleRenderTargets ) {
  51006. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  51007. const attachment = textures[ i ];
  51008. const attachmentProperties = properties.get( attachment );
  51009. let glTextureType = _gl.TEXTURE_2D;
  51010. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  51011. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  51012. }
  51013. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  51014. setTextureParameters( glTextureType, attachment );
  51015. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  51016. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  51017. generateMipmap( glTextureType );
  51018. }
  51019. }
  51020. state.unbindTexture();
  51021. } else {
  51022. let glTextureType = _gl.TEXTURE_2D;
  51023. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  51024. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  51025. }
  51026. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  51027. setTextureParameters( glTextureType, texture );
  51028. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  51029. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  51030. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  51031. }
  51032. } else {
  51033. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  51034. }
  51035. if ( textureNeedsGenerateMipmaps( texture ) ) {
  51036. generateMipmap( glTextureType );
  51037. }
  51038. state.unbindTexture();
  51039. }
  51040. // Setup depth and stencil buffers
  51041. if ( renderTarget.depthBuffer ) {
  51042. setupDepthRenderbuffer( renderTarget );
  51043. }
  51044. }
  51045. function updateRenderTargetMipmap( renderTarget ) {
  51046. const textures = renderTarget.textures;
  51047. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  51048. const texture = textures[ i ];
  51049. if ( textureNeedsGenerateMipmaps( texture ) ) {
  51050. const targetType = getTargetType( renderTarget );
  51051. const webglTexture = properties.get( texture ).__webglTexture;
  51052. state.bindTexture( targetType, webglTexture );
  51053. generateMipmap( targetType );
  51054. state.unbindTexture();
  51055. }
  51056. }
  51057. }
  51058. const invalidationArrayRead = [];
  51059. const invalidationArrayDraw = [];
  51060. function updateMultisampleRenderTarget( renderTarget ) {
  51061. if ( renderTarget.samples > 0 ) {
  51062. if ( useMultisampledRTT( renderTarget ) === false ) {
  51063. const textures = renderTarget.textures;
  51064. const width = renderTarget.width;
  51065. const height = renderTarget.height;
  51066. let mask = _gl.COLOR_BUFFER_BIT;
  51067. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  51068. const renderTargetProperties = properties.get( renderTarget );
  51069. const isMultipleRenderTargets = ( textures.length > 1 );
  51070. // If MRT we need to remove FBO attachments
  51071. if ( isMultipleRenderTargets ) {
  51072. for ( let i = 0; i < textures.length; i ++ ) {
  51073. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51074. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  51075. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  51076. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  51077. }
  51078. }
  51079. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51080. const mipmaps = renderTarget.texture.mipmaps;
  51081. if ( mipmaps && mipmaps.length > 0 ) {
  51082. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  51083. } else {
  51084. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  51085. }
  51086. for ( let i = 0; i < textures.length; i ++ ) {
  51087. if ( renderTarget.resolveDepthBuffer ) {
  51088. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  51089. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  51090. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  51091. }
  51092. if ( isMultipleRenderTargets ) {
  51093. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  51094. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  51095. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  51096. }
  51097. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  51098. if ( supportsInvalidateFramebuffer === true ) {
  51099. invalidationArrayRead.length = 0;
  51100. invalidationArrayDraw.length = 0;
  51101. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  51102. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  51103. invalidationArrayRead.push( depthStyle );
  51104. invalidationArrayDraw.push( depthStyle );
  51105. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  51106. }
  51107. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  51108. }
  51109. }
  51110. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  51111. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  51112. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  51113. if ( isMultipleRenderTargets ) {
  51114. for ( let i = 0; i < textures.length; i ++ ) {
  51115. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51116. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  51117. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  51118. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  51119. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  51120. }
  51121. }
  51122. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  51123. } else {
  51124. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  51125. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  51126. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  51127. }
  51128. }
  51129. }
  51130. }
  51131. function getRenderTargetSamples( renderTarget ) {
  51132. return Math.min( capabilities.maxSamples, renderTarget.samples );
  51133. }
  51134. function useMultisampledRTT( renderTarget ) {
  51135. const renderTargetProperties = properties.get( renderTarget );
  51136. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  51137. }
  51138. function updateVideoTexture( texture ) {
  51139. const frame = info.render.frame;
  51140. // Check the last frame we updated the VideoTexture
  51141. if ( _videoTextures.get( texture ) !== frame ) {
  51142. _videoTextures.set( texture, frame );
  51143. texture.update();
  51144. }
  51145. }
  51146. function verifyColorSpace( texture, image ) {
  51147. const colorSpace = texture.colorSpace;
  51148. const format = texture.format;
  51149. const type = texture.type;
  51150. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  51151. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  51152. // sRGB
  51153. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  51154. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  51155. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  51156. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  51157. }
  51158. } else {
  51159. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  51160. }
  51161. }
  51162. return image;
  51163. }
  51164. function getDimensions( image ) {
  51165. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  51166. // if intrinsic data are not available, fallback to width/height
  51167. _imageDimensions.width = image.naturalWidth || image.width;
  51168. _imageDimensions.height = image.naturalHeight || image.height;
  51169. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  51170. _imageDimensions.width = image.displayWidth;
  51171. _imageDimensions.height = image.displayHeight;
  51172. } else {
  51173. _imageDimensions.width = image.width;
  51174. _imageDimensions.height = image.height;
  51175. }
  51176. return _imageDimensions;
  51177. }
  51178. //
  51179. this.allocateTextureUnit = allocateTextureUnit;
  51180. this.resetTextureUnits = resetTextureUnits;
  51181. this.setTexture2D = setTexture2D;
  51182. this.setTexture2DArray = setTexture2DArray;
  51183. this.setTexture3D = setTexture3D;
  51184. this.setTextureCube = setTextureCube;
  51185. this.rebindTextures = rebindTextures;
  51186. this.setupRenderTarget = setupRenderTarget;
  51187. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  51188. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  51189. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  51190. this.setupFrameBufferTexture = setupFrameBufferTexture;
  51191. this.useMultisampledRTT = useMultisampledRTT;
  51192. this.isReversedDepthBuffer = function () {
  51193. return state.buffers.depth.getReversed();
  51194. };
  51195. }
  51196. function WebGLUtils( gl, extensions ) {
  51197. function convert( p, colorSpace = NoColorSpace ) {
  51198. let extension;
  51199. const transfer = ColorManagement.getTransfer( colorSpace );
  51200. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  51201. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  51202. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  51203. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  51204. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  51205. if ( p === ByteType ) return gl.BYTE;
  51206. if ( p === ShortType ) return gl.SHORT;
  51207. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  51208. if ( p === IntType ) return gl.INT;
  51209. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  51210. if ( p === FloatType ) return gl.FLOAT;
  51211. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  51212. if ( p === AlphaFormat ) return gl.ALPHA;
  51213. if ( p === RGBFormat ) return gl.RGB;
  51214. if ( p === RGBAFormat ) return gl.RGBA;
  51215. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  51216. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  51217. // WebGL2 formats.
  51218. if ( p === RedFormat ) return gl.RED;
  51219. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  51220. if ( p === RGFormat ) return gl.RG;
  51221. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  51222. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  51223. // S3TC
  51224. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  51225. if ( transfer === SRGBTransfer ) {
  51226. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  51227. if ( extension !== null ) {
  51228. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  51229. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  51230. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  51231. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  51232. } else {
  51233. return null;
  51234. }
  51235. } else {
  51236. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  51237. if ( extension !== null ) {
  51238. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  51239. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  51240. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  51241. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  51242. } else {
  51243. return null;
  51244. }
  51245. }
  51246. }
  51247. // PVRTC
  51248. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  51249. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  51250. if ( extension !== null ) {
  51251. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  51252. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  51253. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  51254. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  51255. } else {
  51256. return null;
  51257. }
  51258. }
  51259. // ETC
  51260. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  51261. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  51262. if ( extension !== null ) {
  51263. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  51264. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  51265. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  51266. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  51267. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  51268. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  51269. } else {
  51270. return null;
  51271. }
  51272. }
  51273. // ASTC
  51274. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  51275. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  51276. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  51277. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  51278. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  51279. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  51280. if ( extension !== null ) {
  51281. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  51282. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  51283. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  51284. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  51285. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  51286. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  51287. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  51288. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  51289. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  51290. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  51291. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  51292. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  51293. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  51294. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  51295. } else {
  51296. return null;
  51297. }
  51298. }
  51299. // BPTC
  51300. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  51301. extension = extensions.get( 'EXT_texture_compression_bptc' );
  51302. if ( extension !== null ) {
  51303. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  51304. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  51305. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  51306. } else {
  51307. return null;
  51308. }
  51309. }
  51310. // RGTC
  51311. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  51312. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  51313. if ( extension !== null ) {
  51314. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  51315. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  51316. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  51317. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  51318. } else {
  51319. return null;
  51320. }
  51321. }
  51322. //
  51323. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  51324. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  51325. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  51326. }
  51327. return { convert: convert };
  51328. }
  51329. const _occlusion_vertex = `
  51330. void main() {
  51331. gl_Position = vec4( position, 1.0 );
  51332. }`;
  51333. const _occlusion_fragment = `
  51334. uniform sampler2DArray depthColor;
  51335. uniform float depthWidth;
  51336. uniform float depthHeight;
  51337. void main() {
  51338. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  51339. if ( coord.x >= 1.0 ) {
  51340. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  51341. } else {
  51342. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  51343. }
  51344. }`;
  51345. /**
  51346. * A XR module that manages the access to the Depth Sensing API.
  51347. */
  51348. class WebXRDepthSensing {
  51349. /**
  51350. * Constructs a new depth sensing module.
  51351. */
  51352. constructor() {
  51353. /**
  51354. * An opaque texture representing the depth of the user's environment.
  51355. *
  51356. * @type {?ExternalTexture}
  51357. */
  51358. this.texture = null;
  51359. /**
  51360. * A plane mesh for visualizing the depth texture.
  51361. *
  51362. * @type {?Mesh}
  51363. */
  51364. this.mesh = null;
  51365. /**
  51366. * The depth near value.
  51367. *
  51368. * @type {number}
  51369. */
  51370. this.depthNear = 0;
  51371. /**
  51372. * The depth near far.
  51373. *
  51374. * @type {number}
  51375. */
  51376. this.depthFar = 0;
  51377. }
  51378. /**
  51379. * Inits the depth sensing module
  51380. *
  51381. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  51382. * @param {XRRenderState} renderState - The XR render state.
  51383. */
  51384. init( depthData, renderState ) {
  51385. if ( this.texture === null ) {
  51386. const texture = new ExternalTexture( depthData.texture );
  51387. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  51388. this.depthNear = depthData.depthNear;
  51389. this.depthFar = depthData.depthFar;
  51390. }
  51391. this.texture = texture;
  51392. }
  51393. }
  51394. /**
  51395. * Returns a plane mesh that visualizes the depth texture.
  51396. *
  51397. * @param {ArrayCamera} cameraXR - The XR camera.
  51398. * @return {?Mesh} The plane mesh.
  51399. */
  51400. getMesh( cameraXR ) {
  51401. if ( this.texture !== null ) {
  51402. if ( this.mesh === null ) {
  51403. const viewport = cameraXR.cameras[ 0 ].viewport;
  51404. const material = new ShaderMaterial( {
  51405. vertexShader: _occlusion_vertex,
  51406. fragmentShader: _occlusion_fragment,
  51407. uniforms: {
  51408. depthColor: { value: this.texture },
  51409. depthWidth: { value: viewport.z },
  51410. depthHeight: { value: viewport.w }
  51411. }
  51412. } );
  51413. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  51414. }
  51415. }
  51416. return this.mesh;
  51417. }
  51418. /**
  51419. * Resets the module
  51420. */
  51421. reset() {
  51422. this.texture = null;
  51423. this.mesh = null;
  51424. }
  51425. /**
  51426. * Returns a texture representing the depth of the user's environment.
  51427. *
  51428. * @return {?ExternalTexture} The depth texture.
  51429. */
  51430. getDepthTexture() {
  51431. return this.texture;
  51432. }
  51433. }
  51434. /**
  51435. * This class represents an abstraction of the WebXR Device API and is
  51436. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  51437. * interface that allows users to enable/disable XR and perform XR related
  51438. * tasks like for instance retrieving controllers.
  51439. *
  51440. * @augments EventDispatcher
  51441. * @hideconstructor
  51442. */
  51443. class WebXRManager extends EventDispatcher {
  51444. /**
  51445. * Constructs a new WebGL renderer.
  51446. *
  51447. * @param {WebGLRenderer} renderer - The renderer.
  51448. * @param {WebGL2RenderingContext} gl - The rendering context.
  51449. */
  51450. constructor( renderer, gl ) {
  51451. super();
  51452. const scope = this;
  51453. let session = null;
  51454. let framebufferScaleFactor = 1.0;
  51455. let referenceSpace = null;
  51456. let referenceSpaceType = 'local-floor';
  51457. // Set default foveation to maximum.
  51458. let foveation = 1.0;
  51459. let customReferenceSpace = null;
  51460. let pose = null;
  51461. let glBinding = null;
  51462. let glProjLayer = null;
  51463. let glBaseLayer = null;
  51464. let xrFrame = null;
  51465. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  51466. const depthSensing = new WebXRDepthSensing();
  51467. const cameraAccessTextures = {};
  51468. const attributes = gl.getContextAttributes();
  51469. let initialRenderTarget = null;
  51470. let newRenderTarget = null;
  51471. const controllers = [];
  51472. const controllerInputSources = [];
  51473. const currentSize = new Vector2();
  51474. let currentPixelRatio = null;
  51475. //
  51476. const cameraL = new PerspectiveCamera();
  51477. cameraL.viewport = new Vector4();
  51478. const cameraR = new PerspectiveCamera();
  51479. cameraR.viewport = new Vector4();
  51480. const cameras = [ cameraL, cameraR ];
  51481. const cameraXR = new ArrayCamera();
  51482. let _currentDepthNear = null;
  51483. let _currentDepthFar = null;
  51484. //
  51485. /**
  51486. * Whether the manager's XR camera should be automatically updated or not.
  51487. *
  51488. * @type {boolean}
  51489. * @default true
  51490. */
  51491. this.cameraAutoUpdate = true;
  51492. /**
  51493. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  51494. * if you are going to use XR in your app.
  51495. *
  51496. * @type {boolean}
  51497. * @default false
  51498. */
  51499. this.enabled = false;
  51500. /**
  51501. * Whether XR presentation is active or not.
  51502. *
  51503. * @type {boolean}
  51504. * @readonly
  51505. * @default false
  51506. */
  51507. this.isPresenting = false;
  51508. /**
  51509. * Returns a group representing the `target ray` space of the XR controller.
  51510. * Use this space for visualizing 3D objects that support the user in pointing
  51511. * tasks like UI interaction.
  51512. *
  51513. * @param {number} index - The index of the controller.
  51514. * @return {Group} A group representing the `target ray` space.
  51515. */
  51516. this.getController = function ( index ) {
  51517. let controller = controllers[ index ];
  51518. if ( controller === undefined ) {
  51519. controller = new WebXRController();
  51520. controllers[ index ] = controller;
  51521. }
  51522. return controller.getTargetRaySpace();
  51523. };
  51524. /**
  51525. * Returns a group representing the `grip` space of the XR controller.
  51526. * Use this space for visualizing 3D objects that support the user in pointing
  51527. * tasks like UI interaction.
  51528. *
  51529. * Note: If you want to show something in the user's hand AND offer a
  51530. * pointing ray at the same time, you'll want to attached the handheld object
  51531. * to the group returned by `getControllerGrip()` and the ray to the
  51532. * group returned by `getController()`. The idea is to have two
  51533. * different groups in two different coordinate spaces for the same WebXR
  51534. * controller.
  51535. *
  51536. * @param {number} index - The index of the controller.
  51537. * @return {Group} A group representing the `grip` space.
  51538. */
  51539. this.getControllerGrip = function ( index ) {
  51540. let controller = controllers[ index ];
  51541. if ( controller === undefined ) {
  51542. controller = new WebXRController();
  51543. controllers[ index ] = controller;
  51544. }
  51545. return controller.getGripSpace();
  51546. };
  51547. /**
  51548. * Returns a group representing the `hand` space of the XR controller.
  51549. * Use this space for visualizing 3D objects that support the user in pointing
  51550. * tasks like UI interaction.
  51551. *
  51552. * @param {number} index - The index of the controller.
  51553. * @return {Group} A group representing the `hand` space.
  51554. */
  51555. this.getHand = function ( index ) {
  51556. let controller = controllers[ index ];
  51557. if ( controller === undefined ) {
  51558. controller = new WebXRController();
  51559. controllers[ index ] = controller;
  51560. }
  51561. return controller.getHandSpace();
  51562. };
  51563. //
  51564. function onSessionEvent( event ) {
  51565. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  51566. if ( controllerIndex === -1 ) {
  51567. return;
  51568. }
  51569. const controller = controllers[ controllerIndex ];
  51570. if ( controller !== undefined ) {
  51571. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  51572. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  51573. }
  51574. }
  51575. function onSessionEnd() {
  51576. session.removeEventListener( 'select', onSessionEvent );
  51577. session.removeEventListener( 'selectstart', onSessionEvent );
  51578. session.removeEventListener( 'selectend', onSessionEvent );
  51579. session.removeEventListener( 'squeeze', onSessionEvent );
  51580. session.removeEventListener( 'squeezestart', onSessionEvent );
  51581. session.removeEventListener( 'squeezeend', onSessionEvent );
  51582. session.removeEventListener( 'end', onSessionEnd );
  51583. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  51584. for ( let i = 0; i < controllers.length; i ++ ) {
  51585. const inputSource = controllerInputSources[ i ];
  51586. if ( inputSource === null ) continue;
  51587. controllerInputSources[ i ] = null;
  51588. controllers[ i ].disconnect( inputSource );
  51589. }
  51590. _currentDepthNear = null;
  51591. _currentDepthFar = null;
  51592. depthSensing.reset();
  51593. for ( const key in cameraAccessTextures ) {
  51594. delete cameraAccessTextures[ key ];
  51595. }
  51596. // restore framebuffer/rendering state
  51597. renderer.setRenderTarget( initialRenderTarget );
  51598. glBaseLayer = null;
  51599. glProjLayer = null;
  51600. glBinding = null;
  51601. session = null;
  51602. newRenderTarget = null;
  51603. //
  51604. animation.stop();
  51605. scope.isPresenting = false;
  51606. renderer.setPixelRatio( currentPixelRatio );
  51607. renderer.setSize( currentSize.width, currentSize.height, false );
  51608. scope.dispatchEvent( { type: 'sessionend' } );
  51609. }
  51610. /**
  51611. * Sets the framebuffer scale factor.
  51612. *
  51613. * This method can not be used during a XR session.
  51614. *
  51615. * @param {number} value - The framebuffer scale factor.
  51616. */
  51617. this.setFramebufferScaleFactor = function ( value ) {
  51618. framebufferScaleFactor = value;
  51619. if ( scope.isPresenting === true ) {
  51620. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51621. }
  51622. };
  51623. /**
  51624. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51625. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51626. * improve tracking. Default is `local-floor`. Valid values can be found here
  51627. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51628. *
  51629. * This method can not be used during a XR session.
  51630. *
  51631. * @param {string} value - The reference space type.
  51632. */
  51633. this.setReferenceSpaceType = function ( value ) {
  51634. referenceSpaceType = value;
  51635. if ( scope.isPresenting === true ) {
  51636. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51637. }
  51638. };
  51639. /**
  51640. * Returns the XR reference space.
  51641. *
  51642. * @return {XRReferenceSpace} The XR reference space.
  51643. */
  51644. this.getReferenceSpace = function () {
  51645. return customReferenceSpace || referenceSpace;
  51646. };
  51647. /**
  51648. * Sets a custom XR reference space.
  51649. *
  51650. * @param {XRReferenceSpace} space - The XR reference space.
  51651. */
  51652. this.setReferenceSpace = function ( space ) {
  51653. customReferenceSpace = space;
  51654. };
  51655. /**
  51656. * Returns the current base layer.
  51657. *
  51658. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51659. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51660. *
  51661. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51662. */
  51663. this.getBaseLayer = function () {
  51664. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51665. };
  51666. /**
  51667. * Returns the current XR binding.
  51668. *
  51669. * Creates a new binding if needed and the browser is
  51670. * capable of doing so.
  51671. *
  51672. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51673. */
  51674. this.getBinding = function () {
  51675. if ( glBinding === null && supportsGlBinding ) {
  51676. glBinding = new XRWebGLBinding( session, gl );
  51677. }
  51678. return glBinding;
  51679. };
  51680. /**
  51681. * Returns the current XR frame.
  51682. *
  51683. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51684. */
  51685. this.getFrame = function () {
  51686. return xrFrame;
  51687. };
  51688. /**
  51689. * Returns the current XR session.
  51690. *
  51691. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51692. */
  51693. this.getSession = function () {
  51694. return session;
  51695. };
  51696. /**
  51697. * After a XR session has been requested usually with one of the `*Button` modules, it
  51698. * is injected into the renderer with this method. This method triggers the start of
  51699. * the actual XR rendering.
  51700. *
  51701. * @async
  51702. * @param {XRSession} value - The XR session to set.
  51703. * @return {Promise} A Promise that resolves when the session has been set.
  51704. */
  51705. this.setSession = async function ( value ) {
  51706. session = value;
  51707. if ( session !== null ) {
  51708. initialRenderTarget = renderer.getRenderTarget();
  51709. session.addEventListener( 'select', onSessionEvent );
  51710. session.addEventListener( 'selectstart', onSessionEvent );
  51711. session.addEventListener( 'selectend', onSessionEvent );
  51712. session.addEventListener( 'squeeze', onSessionEvent );
  51713. session.addEventListener( 'squeezestart', onSessionEvent );
  51714. session.addEventListener( 'squeezeend', onSessionEvent );
  51715. session.addEventListener( 'end', onSessionEnd );
  51716. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51717. if ( attributes.xrCompatible !== true ) {
  51718. await gl.makeXRCompatible();
  51719. }
  51720. currentPixelRatio = renderer.getPixelRatio();
  51721. renderer.getSize( currentSize );
  51722. // Check that the browser implements the necessary APIs to use an
  51723. // XRProjectionLayer rather than an XRWebGLLayer
  51724. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51725. if ( ! supportsLayers ) {
  51726. const layerInit = {
  51727. antialias: attributes.antialias,
  51728. alpha: true,
  51729. depth: attributes.depth,
  51730. stencil: attributes.stencil,
  51731. framebufferScaleFactor: framebufferScaleFactor
  51732. };
  51733. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51734. session.updateRenderState( { baseLayer: glBaseLayer } );
  51735. renderer.setPixelRatio( 1 );
  51736. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51737. newRenderTarget = new WebGLRenderTarget(
  51738. glBaseLayer.framebufferWidth,
  51739. glBaseLayer.framebufferHeight,
  51740. {
  51741. format: RGBAFormat,
  51742. type: UnsignedByteType,
  51743. colorSpace: renderer.outputColorSpace,
  51744. stencilBuffer: attributes.stencil,
  51745. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51746. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51747. }
  51748. );
  51749. } else {
  51750. let depthFormat = null;
  51751. let depthType = null;
  51752. let glDepthFormat = null;
  51753. if ( attributes.depth ) {
  51754. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51755. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51756. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51757. }
  51758. const projectionlayerInit = {
  51759. colorFormat: gl.RGBA8,
  51760. depthFormat: glDepthFormat,
  51761. scaleFactor: framebufferScaleFactor
  51762. };
  51763. glBinding = this.getBinding();
  51764. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51765. session.updateRenderState( { layers: [ glProjLayer ] } );
  51766. renderer.setPixelRatio( 1 );
  51767. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51768. newRenderTarget = new WebGLRenderTarget(
  51769. glProjLayer.textureWidth,
  51770. glProjLayer.textureHeight,
  51771. {
  51772. format: RGBAFormat,
  51773. type: UnsignedByteType,
  51774. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51775. stencilBuffer: attributes.stencil,
  51776. colorSpace: renderer.outputColorSpace,
  51777. samples: attributes.antialias ? 4 : 0,
  51778. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51779. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51780. } );
  51781. }
  51782. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51783. this.setFoveation( foveation );
  51784. customReferenceSpace = null;
  51785. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51786. animation.setContext( session );
  51787. animation.start();
  51788. scope.isPresenting = true;
  51789. scope.dispatchEvent( { type: 'sessionstart' } );
  51790. }
  51791. };
  51792. /**
  51793. * Returns the environment blend mode from the current XR session.
  51794. *
  51795. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51796. */
  51797. this.getEnvironmentBlendMode = function () {
  51798. if ( session !== null ) {
  51799. return session.environmentBlendMode;
  51800. }
  51801. };
  51802. /**
  51803. * Returns the current depth texture computed via depth sensing.
  51804. *
  51805. * See {@link WebXRDepthSensing#getDepthTexture}.
  51806. *
  51807. * @return {?Texture} The depth texture.
  51808. */
  51809. this.getDepthTexture = function () {
  51810. return depthSensing.getDepthTexture();
  51811. };
  51812. function onInputSourcesChange( event ) {
  51813. // Notify disconnected
  51814. for ( let i = 0; i < event.removed.length; i ++ ) {
  51815. const inputSource = event.removed[ i ];
  51816. const index = controllerInputSources.indexOf( inputSource );
  51817. if ( index >= 0 ) {
  51818. controllerInputSources[ index ] = null;
  51819. controllers[ index ].disconnect( inputSource );
  51820. }
  51821. }
  51822. // Notify connected
  51823. for ( let i = 0; i < event.added.length; i ++ ) {
  51824. const inputSource = event.added[ i ];
  51825. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51826. if ( controllerIndex === -1 ) {
  51827. // Assign input source a controller that currently has no input source
  51828. for ( let i = 0; i < controllers.length; i ++ ) {
  51829. if ( i >= controllerInputSources.length ) {
  51830. controllerInputSources.push( inputSource );
  51831. controllerIndex = i;
  51832. break;
  51833. } else if ( controllerInputSources[ i ] === null ) {
  51834. controllerInputSources[ i ] = inputSource;
  51835. controllerIndex = i;
  51836. break;
  51837. }
  51838. }
  51839. // If all controllers do currently receive input we ignore new ones
  51840. if ( controllerIndex === -1 ) break;
  51841. }
  51842. const controller = controllers[ controllerIndex ];
  51843. if ( controller ) {
  51844. controller.connect( inputSource );
  51845. }
  51846. }
  51847. }
  51848. //
  51849. const cameraLPos = new Vector3();
  51850. const cameraRPos = new Vector3();
  51851. /**
  51852. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51853. * the cameras' projection and world matrices have already been set.
  51854. * And that near and far planes are identical for both cameras.
  51855. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51856. *
  51857. * @param {ArrayCamera} camera - The camera to update.
  51858. * @param {PerspectiveCamera} cameraL - The left camera.
  51859. * @param {PerspectiveCamera} cameraR - The right camera.
  51860. */
  51861. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51862. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51863. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51864. const ipd = cameraLPos.distanceTo( cameraRPos );
  51865. const projL = cameraL.projectionMatrix.elements;
  51866. const projR = cameraR.projectionMatrix.elements;
  51867. // VR systems will have identical far and near planes, and
  51868. // most likely identical top and bottom frustum extents.
  51869. // Use the left camera for these values.
  51870. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51871. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51872. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51873. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51874. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51875. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51876. const left = near * leftFov;
  51877. const right = near * rightFov;
  51878. // Calculate the new camera's position offset from the
  51879. // left camera. xOffset should be roughly half `ipd`.
  51880. const zOffset = ipd / ( - leftFov + rightFov );
  51881. const xOffset = zOffset * - leftFov;
  51882. // TODO: Better way to apply this offset?
  51883. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51884. camera.translateX( xOffset );
  51885. camera.translateZ( zOffset );
  51886. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51887. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51888. // Check if the projection uses an infinite far plane.
  51889. if ( projL[ 10 ] === -1 ) {
  51890. // Use the projection matrix from the left eye.
  51891. // The camera offset is sufficient to include the view volumes
  51892. // of both eyes (assuming symmetric projections).
  51893. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51894. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51895. } else {
  51896. // Find the union of the frustum values of the cameras and scale
  51897. // the values so that the near plane's position does not change in world space,
  51898. // although must now be relative to the new union camera.
  51899. const near2 = near + zOffset;
  51900. const far2 = far + zOffset;
  51901. const left2 = left - xOffset;
  51902. const right2 = right + ( ipd - xOffset );
  51903. const top2 = topFov * far / far2 * near2;
  51904. const bottom2 = bottomFov * far / far2 * near2;
  51905. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51906. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51907. }
  51908. }
  51909. function updateCamera( camera, parent ) {
  51910. if ( parent === null ) {
  51911. camera.matrixWorld.copy( camera.matrix );
  51912. } else {
  51913. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51914. }
  51915. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51916. }
  51917. /**
  51918. * Updates the state of the XR camera. Use this method on app level if you
  51919. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51920. * camera of the scene as a parameter. The passed in camera's transformation
  51921. * is automatically adjusted to the position of the XR camera when calling
  51922. * this method.
  51923. *
  51924. * @param {Camera} camera - The camera.
  51925. */
  51926. this.updateCamera = function ( camera ) {
  51927. if ( session === null ) return;
  51928. let depthNear = camera.near;
  51929. let depthFar = camera.far;
  51930. if ( depthSensing.texture !== null ) {
  51931. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51932. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51933. }
  51934. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  51935. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  51936. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  51937. // Note that the new renderState won't apply until the next frame. See #18320
  51938. session.updateRenderState( {
  51939. depthNear: cameraXR.near,
  51940. depthFar: cameraXR.far
  51941. } );
  51942. _currentDepthNear = cameraXR.near;
  51943. _currentDepthFar = cameraXR.far;
  51944. }
  51945. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  51946. cameraXR.layers.mask = camera.layers.mask | 0b110;
  51947. cameraL.layers.mask = cameraXR.layers.mask & -5;
  51948. cameraR.layers.mask = cameraXR.layers.mask & -3;
  51949. const parent = camera.parent;
  51950. const cameras = cameraXR.cameras;
  51951. updateCamera( cameraXR, parent );
  51952. for ( let i = 0; i < cameras.length; i ++ ) {
  51953. updateCamera( cameras[ i ], parent );
  51954. }
  51955. // update projection matrix for proper view frustum culling
  51956. if ( cameras.length === 2 ) {
  51957. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  51958. } else {
  51959. // assume single camera setup (AR)
  51960. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  51961. }
  51962. // update user camera and its children
  51963. updateUserCamera( camera, cameraXR, parent );
  51964. };
  51965. function updateUserCamera( camera, cameraXR, parent ) {
  51966. if ( parent === null ) {
  51967. camera.matrix.copy( cameraXR.matrixWorld );
  51968. } else {
  51969. camera.matrix.copy( parent.matrixWorld );
  51970. camera.matrix.invert();
  51971. camera.matrix.multiply( cameraXR.matrixWorld );
  51972. }
  51973. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51974. camera.updateMatrixWorld( true );
  51975. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  51976. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  51977. if ( camera.isPerspectiveCamera ) {
  51978. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  51979. camera.zoom = 1;
  51980. }
  51981. }
  51982. /**
  51983. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  51984. * of the active XR session. For each view it holds a separate camera object.
  51985. *
  51986. * The camera's `fov` is currently not used and does not reflect the fov of
  51987. * the XR camera. If you need the fov on app level, you have to compute in
  51988. * manually from the XR camera's projection matrices.
  51989. *
  51990. * @return {ArrayCamera} The XR camera.
  51991. */
  51992. this.getCamera = function () {
  51993. return cameraXR;
  51994. };
  51995. /**
  51996. * Returns the amount of foveation used by the XR compositor for the projection layer.
  51997. *
  51998. * @return {number|undefined} The amount of foveation.
  51999. */
  52000. this.getFoveation = function () {
  52001. if ( glProjLayer === null && glBaseLayer === null ) {
  52002. return undefined;
  52003. }
  52004. return foveation;
  52005. };
  52006. /**
  52007. * Sets the foveation value.
  52008. *
  52009. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  52010. * and `1` means maximum foveation (the edges render at lower resolution).
  52011. */
  52012. this.setFoveation = function ( value ) {
  52013. // 0 = no foveation = full resolution
  52014. // 1 = maximum foveation = the edges render at lower resolution
  52015. foveation = value;
  52016. if ( glProjLayer !== null ) {
  52017. glProjLayer.fixedFoveation = value;
  52018. }
  52019. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  52020. glBaseLayer.fixedFoveation = value;
  52021. }
  52022. };
  52023. /**
  52024. * Returns `true` if depth sensing is supported.
  52025. *
  52026. * @return {boolean} Whether depth sensing is supported or not.
  52027. */
  52028. this.hasDepthSensing = function () {
  52029. return depthSensing.texture !== null;
  52030. };
  52031. /**
  52032. * Returns the depth sensing mesh.
  52033. *
  52034. * See {@link WebXRDepthSensing#getMesh}.
  52035. *
  52036. * @return {Mesh} The depth sensing mesh.
  52037. */
  52038. this.getDepthSensingMesh = function () {
  52039. return depthSensing.getMesh( cameraXR );
  52040. };
  52041. /**
  52042. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  52043. * Only available during the current animation loop.
  52044. *
  52045. * @param {XRCamera} xrCamera - The camera to query.
  52046. * @return {?Texture} An opaque texture representing the current raw camera frame.
  52047. */
  52048. this.getCameraTexture = function ( xrCamera ) {
  52049. return cameraAccessTextures[ xrCamera ];
  52050. };
  52051. // Animation Loop
  52052. let onAnimationFrameCallback = null;
  52053. function onAnimationFrame( time, frame ) {
  52054. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  52055. xrFrame = frame;
  52056. if ( pose !== null ) {
  52057. const views = pose.views;
  52058. if ( glBaseLayer !== null ) {
  52059. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  52060. renderer.setRenderTarget( newRenderTarget );
  52061. }
  52062. let cameraXRNeedsUpdate = false;
  52063. // check if it's necessary to rebuild cameraXR's camera list
  52064. if ( views.length !== cameraXR.cameras.length ) {
  52065. cameraXR.cameras.length = 0;
  52066. cameraXRNeedsUpdate = true;
  52067. }
  52068. for ( let i = 0; i < views.length; i ++ ) {
  52069. const view = views[ i ];
  52070. let viewport = null;
  52071. if ( glBaseLayer !== null ) {
  52072. viewport = glBaseLayer.getViewport( view );
  52073. } else {
  52074. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  52075. viewport = glSubImage.viewport;
  52076. // For side-by-side projection, we only produce a single texture for both eyes.
  52077. if ( i === 0 ) {
  52078. renderer.setRenderTargetTextures(
  52079. newRenderTarget,
  52080. glSubImage.colorTexture,
  52081. glSubImage.depthStencilTexture );
  52082. renderer.setRenderTarget( newRenderTarget );
  52083. }
  52084. }
  52085. let camera = cameras[ i ];
  52086. if ( camera === undefined ) {
  52087. camera = new PerspectiveCamera();
  52088. camera.layers.enable( i );
  52089. camera.viewport = new Vector4();
  52090. cameras[ i ] = camera;
  52091. }
  52092. camera.matrix.fromArray( view.transform.matrix );
  52093. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  52094. camera.projectionMatrix.fromArray( view.projectionMatrix );
  52095. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  52096. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  52097. if ( i === 0 ) {
  52098. cameraXR.matrix.copy( camera.matrix );
  52099. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  52100. }
  52101. if ( cameraXRNeedsUpdate === true ) {
  52102. cameraXR.cameras.push( camera );
  52103. }
  52104. }
  52105. //
  52106. const enabledFeatures = session.enabledFeatures;
  52107. const gpuDepthSensingEnabled = enabledFeatures &&
  52108. enabledFeatures.includes( 'depth-sensing' ) &&
  52109. session.depthUsage == 'gpu-optimized';
  52110. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  52111. glBinding = scope.getBinding();
  52112. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  52113. if ( depthData && depthData.isValid && depthData.texture ) {
  52114. depthSensing.init( depthData, session.renderState );
  52115. }
  52116. }
  52117. const cameraAccessEnabled = enabledFeatures &&
  52118. enabledFeatures.includes( 'camera-access' );
  52119. if ( cameraAccessEnabled && supportsGlBinding ) {
  52120. renderer.state.unbindTexture();
  52121. glBinding = scope.getBinding();
  52122. for ( let i = 0; i < views.length; i ++ ) {
  52123. const camera = views[ i ].camera;
  52124. if ( camera ) {
  52125. let cameraTex = cameraAccessTextures[ camera ];
  52126. if ( ! cameraTex ) {
  52127. cameraTex = new ExternalTexture();
  52128. cameraAccessTextures[ camera ] = cameraTex;
  52129. }
  52130. const glTexture = glBinding.getCameraImage( camera );
  52131. cameraTex.sourceTexture = glTexture;
  52132. }
  52133. }
  52134. }
  52135. }
  52136. //
  52137. for ( let i = 0; i < controllers.length; i ++ ) {
  52138. const inputSource = controllerInputSources[ i ];
  52139. const controller = controllers[ i ];
  52140. if ( inputSource !== null && controller !== undefined ) {
  52141. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  52142. }
  52143. }
  52144. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  52145. if ( frame.detectedPlanes ) {
  52146. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  52147. }
  52148. xrFrame = null;
  52149. }
  52150. const animation = new WebGLAnimation();
  52151. animation.setAnimationLoop( onAnimationFrame );
  52152. this.setAnimationLoop = function ( callback ) {
  52153. onAnimationFrameCallback = callback;
  52154. };
  52155. this.dispose = function () {};
  52156. }
  52157. }
  52158. const _e1 = /*@__PURE__*/ new Euler();
  52159. const _m1 = /*@__PURE__*/ new Matrix4();
  52160. function WebGLMaterials( renderer, properties ) {
  52161. function refreshTransformUniform( map, uniform ) {
  52162. if ( map.matrixAutoUpdate === true ) {
  52163. map.updateMatrix();
  52164. }
  52165. uniform.value.copy( map.matrix );
  52166. }
  52167. function refreshFogUniforms( uniforms, fog ) {
  52168. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  52169. if ( fog.isFog ) {
  52170. uniforms.fogNear.value = fog.near;
  52171. uniforms.fogFar.value = fog.far;
  52172. } else if ( fog.isFogExp2 ) {
  52173. uniforms.fogDensity.value = fog.density;
  52174. }
  52175. }
  52176. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  52177. if ( material.isMeshBasicMaterial ) {
  52178. refreshUniformsCommon( uniforms, material );
  52179. } else if ( material.isMeshLambertMaterial ) {
  52180. refreshUniformsCommon( uniforms, material );
  52181. if ( material.envMap ) {
  52182. uniforms.envMapIntensity.value = material.envMapIntensity;
  52183. }
  52184. } else if ( material.isMeshToonMaterial ) {
  52185. refreshUniformsCommon( uniforms, material );
  52186. refreshUniformsToon( uniforms, material );
  52187. } else if ( material.isMeshPhongMaterial ) {
  52188. refreshUniformsCommon( uniforms, material );
  52189. refreshUniformsPhong( uniforms, material );
  52190. if ( material.envMap ) {
  52191. uniforms.envMapIntensity.value = material.envMapIntensity;
  52192. }
  52193. } else if ( material.isMeshStandardMaterial ) {
  52194. refreshUniformsCommon( uniforms, material );
  52195. refreshUniformsStandard( uniforms, material );
  52196. if ( material.isMeshPhysicalMaterial ) {
  52197. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  52198. }
  52199. } else if ( material.isMeshMatcapMaterial ) {
  52200. refreshUniformsCommon( uniforms, material );
  52201. refreshUniformsMatcap( uniforms, material );
  52202. } else if ( material.isMeshDepthMaterial ) {
  52203. refreshUniformsCommon( uniforms, material );
  52204. } else if ( material.isMeshDistanceMaterial ) {
  52205. refreshUniformsCommon( uniforms, material );
  52206. refreshUniformsDistance( uniforms, material );
  52207. } else if ( material.isMeshNormalMaterial ) {
  52208. refreshUniformsCommon( uniforms, material );
  52209. } else if ( material.isLineBasicMaterial ) {
  52210. refreshUniformsLine( uniforms, material );
  52211. if ( material.isLineDashedMaterial ) {
  52212. refreshUniformsDash( uniforms, material );
  52213. }
  52214. } else if ( material.isPointsMaterial ) {
  52215. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  52216. } else if ( material.isSpriteMaterial ) {
  52217. refreshUniformsSprites( uniforms, material );
  52218. } else if ( material.isShadowMaterial ) {
  52219. uniforms.color.value.copy( material.color );
  52220. uniforms.opacity.value = material.opacity;
  52221. } else if ( material.isShaderMaterial ) {
  52222. material.uniformsNeedUpdate = false; // #15581
  52223. }
  52224. }
  52225. function refreshUniformsCommon( uniforms, material ) {
  52226. uniforms.opacity.value = material.opacity;
  52227. if ( material.color ) {
  52228. uniforms.diffuse.value.copy( material.color );
  52229. }
  52230. if ( material.emissive ) {
  52231. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  52232. }
  52233. if ( material.map ) {
  52234. uniforms.map.value = material.map;
  52235. refreshTransformUniform( material.map, uniforms.mapTransform );
  52236. }
  52237. if ( material.alphaMap ) {
  52238. uniforms.alphaMap.value = material.alphaMap;
  52239. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52240. }
  52241. if ( material.bumpMap ) {
  52242. uniforms.bumpMap.value = material.bumpMap;
  52243. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  52244. uniforms.bumpScale.value = material.bumpScale;
  52245. if ( material.side === BackSide ) {
  52246. uniforms.bumpScale.value *= -1;
  52247. }
  52248. }
  52249. if ( material.normalMap ) {
  52250. uniforms.normalMap.value = material.normalMap;
  52251. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  52252. uniforms.normalScale.value.copy( material.normalScale );
  52253. if ( material.side === BackSide ) {
  52254. uniforms.normalScale.value.negate();
  52255. }
  52256. }
  52257. if ( material.displacementMap ) {
  52258. uniforms.displacementMap.value = material.displacementMap;
  52259. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  52260. uniforms.displacementScale.value = material.displacementScale;
  52261. uniforms.displacementBias.value = material.displacementBias;
  52262. }
  52263. if ( material.emissiveMap ) {
  52264. uniforms.emissiveMap.value = material.emissiveMap;
  52265. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  52266. }
  52267. if ( material.specularMap ) {
  52268. uniforms.specularMap.value = material.specularMap;
  52269. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  52270. }
  52271. if ( material.alphaTest > 0 ) {
  52272. uniforms.alphaTest.value = material.alphaTest;
  52273. }
  52274. const materialProperties = properties.get( material );
  52275. const envMap = materialProperties.envMap;
  52276. const envMapRotation = materialProperties.envMapRotation;
  52277. if ( envMap ) {
  52278. uniforms.envMap.value = envMap;
  52279. _e1.copy( envMapRotation );
  52280. // accommodate left-handed frame
  52281. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  52282. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  52283. // environment maps which are not cube render targets or PMREMs follow a different convention
  52284. _e1.y *= -1;
  52285. _e1.z *= -1;
  52286. }
  52287. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  52288. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  52289. uniforms.reflectivity.value = material.reflectivity;
  52290. uniforms.ior.value = material.ior;
  52291. uniforms.refractionRatio.value = material.refractionRatio;
  52292. }
  52293. if ( material.lightMap ) {
  52294. uniforms.lightMap.value = material.lightMap;
  52295. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  52296. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  52297. }
  52298. if ( material.aoMap ) {
  52299. uniforms.aoMap.value = material.aoMap;
  52300. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  52301. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  52302. }
  52303. }
  52304. function refreshUniformsLine( uniforms, material ) {
  52305. uniforms.diffuse.value.copy( material.color );
  52306. uniforms.opacity.value = material.opacity;
  52307. if ( material.map ) {
  52308. uniforms.map.value = material.map;
  52309. refreshTransformUniform( material.map, uniforms.mapTransform );
  52310. }
  52311. }
  52312. function refreshUniformsDash( uniforms, material ) {
  52313. uniforms.dashSize.value = material.dashSize;
  52314. uniforms.totalSize.value = material.dashSize + material.gapSize;
  52315. uniforms.scale.value = material.scale;
  52316. }
  52317. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  52318. uniforms.diffuse.value.copy( material.color );
  52319. uniforms.opacity.value = material.opacity;
  52320. uniforms.size.value = material.size * pixelRatio;
  52321. uniforms.scale.value = height * 0.5;
  52322. if ( material.map ) {
  52323. uniforms.map.value = material.map;
  52324. refreshTransformUniform( material.map, uniforms.uvTransform );
  52325. }
  52326. if ( material.alphaMap ) {
  52327. uniforms.alphaMap.value = material.alphaMap;
  52328. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52329. }
  52330. if ( material.alphaTest > 0 ) {
  52331. uniforms.alphaTest.value = material.alphaTest;
  52332. }
  52333. }
  52334. function refreshUniformsSprites( uniforms, material ) {
  52335. uniforms.diffuse.value.copy( material.color );
  52336. uniforms.opacity.value = material.opacity;
  52337. uniforms.rotation.value = material.rotation;
  52338. if ( material.map ) {
  52339. uniforms.map.value = material.map;
  52340. refreshTransformUniform( material.map, uniforms.mapTransform );
  52341. }
  52342. if ( material.alphaMap ) {
  52343. uniforms.alphaMap.value = material.alphaMap;
  52344. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52345. }
  52346. if ( material.alphaTest > 0 ) {
  52347. uniforms.alphaTest.value = material.alphaTest;
  52348. }
  52349. }
  52350. function refreshUniformsPhong( uniforms, material ) {
  52351. uniforms.specular.value.copy( material.specular );
  52352. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  52353. }
  52354. function refreshUniformsToon( uniforms, material ) {
  52355. if ( material.gradientMap ) {
  52356. uniforms.gradientMap.value = material.gradientMap;
  52357. }
  52358. }
  52359. function refreshUniformsStandard( uniforms, material ) {
  52360. uniforms.metalness.value = material.metalness;
  52361. if ( material.metalnessMap ) {
  52362. uniforms.metalnessMap.value = material.metalnessMap;
  52363. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  52364. }
  52365. uniforms.roughness.value = material.roughness;
  52366. if ( material.roughnessMap ) {
  52367. uniforms.roughnessMap.value = material.roughnessMap;
  52368. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  52369. }
  52370. if ( material.envMap ) {
  52371. //uniforms.envMap.value = material.envMap; // part of uniforms common
  52372. uniforms.envMapIntensity.value = material.envMapIntensity;
  52373. }
  52374. }
  52375. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  52376. uniforms.ior.value = material.ior; // also part of uniforms common
  52377. if ( material.sheen > 0 ) {
  52378. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  52379. uniforms.sheenRoughness.value = material.sheenRoughness;
  52380. if ( material.sheenColorMap ) {
  52381. uniforms.sheenColorMap.value = material.sheenColorMap;
  52382. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  52383. }
  52384. if ( material.sheenRoughnessMap ) {
  52385. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  52386. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  52387. }
  52388. }
  52389. if ( material.clearcoat > 0 ) {
  52390. uniforms.clearcoat.value = material.clearcoat;
  52391. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  52392. if ( material.clearcoatMap ) {
  52393. uniforms.clearcoatMap.value = material.clearcoatMap;
  52394. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  52395. }
  52396. if ( material.clearcoatRoughnessMap ) {
  52397. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  52398. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  52399. }
  52400. if ( material.clearcoatNormalMap ) {
  52401. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  52402. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  52403. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  52404. if ( material.side === BackSide ) {
  52405. uniforms.clearcoatNormalScale.value.negate();
  52406. }
  52407. }
  52408. }
  52409. if ( material.dispersion > 0 ) {
  52410. uniforms.dispersion.value = material.dispersion;
  52411. }
  52412. if ( material.iridescence > 0 ) {
  52413. uniforms.iridescence.value = material.iridescence;
  52414. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  52415. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  52416. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  52417. if ( material.iridescenceMap ) {
  52418. uniforms.iridescenceMap.value = material.iridescenceMap;
  52419. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  52420. }
  52421. if ( material.iridescenceThicknessMap ) {
  52422. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  52423. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  52424. }
  52425. }
  52426. if ( material.transmission > 0 ) {
  52427. uniforms.transmission.value = material.transmission;
  52428. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  52429. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  52430. if ( material.transmissionMap ) {
  52431. uniforms.transmissionMap.value = material.transmissionMap;
  52432. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  52433. }
  52434. uniforms.thickness.value = material.thickness;
  52435. if ( material.thicknessMap ) {
  52436. uniforms.thicknessMap.value = material.thicknessMap;
  52437. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  52438. }
  52439. uniforms.attenuationDistance.value = material.attenuationDistance;
  52440. uniforms.attenuationColor.value.copy( material.attenuationColor );
  52441. }
  52442. if ( material.anisotropy > 0 ) {
  52443. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  52444. if ( material.anisotropyMap ) {
  52445. uniforms.anisotropyMap.value = material.anisotropyMap;
  52446. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  52447. }
  52448. }
  52449. uniforms.specularIntensity.value = material.specularIntensity;
  52450. uniforms.specularColor.value.copy( material.specularColor );
  52451. if ( material.specularColorMap ) {
  52452. uniforms.specularColorMap.value = material.specularColorMap;
  52453. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  52454. }
  52455. if ( material.specularIntensityMap ) {
  52456. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  52457. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  52458. }
  52459. }
  52460. function refreshUniformsMatcap( uniforms, material ) {
  52461. if ( material.matcap ) {
  52462. uniforms.matcap.value = material.matcap;
  52463. }
  52464. }
  52465. function refreshUniformsDistance( uniforms, material ) {
  52466. const light = properties.get( material ).light;
  52467. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  52468. uniforms.nearDistance.value = light.shadow.camera.near;
  52469. uniforms.farDistance.value = light.shadow.camera.far;
  52470. }
  52471. return {
  52472. refreshFogUniforms: refreshFogUniforms,
  52473. refreshMaterialUniforms: refreshMaterialUniforms
  52474. };
  52475. }
  52476. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  52477. let buffers = {};
  52478. let updateList = {};
  52479. let allocatedBindingPoints = [];
  52480. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  52481. function bind( uniformsGroup, program ) {
  52482. const webglProgram = program.program;
  52483. state.uniformBlockBinding( uniformsGroup, webglProgram );
  52484. }
  52485. function update( uniformsGroup, program ) {
  52486. let buffer = buffers[ uniformsGroup.id ];
  52487. if ( buffer === undefined ) {
  52488. prepareUniformsGroup( uniformsGroup );
  52489. buffer = createBuffer( uniformsGroup );
  52490. buffers[ uniformsGroup.id ] = buffer;
  52491. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  52492. }
  52493. // ensure to update the binding points/block indices mapping for this program
  52494. const webglProgram = program.program;
  52495. state.updateUBOMapping( uniformsGroup, webglProgram );
  52496. // update UBO once per frame
  52497. const frame = info.render.frame;
  52498. if ( updateList[ uniformsGroup.id ] !== frame ) {
  52499. updateBufferData( uniformsGroup );
  52500. updateList[ uniformsGroup.id ] = frame;
  52501. }
  52502. }
  52503. function createBuffer( uniformsGroup ) {
  52504. // the setup of an UBO is independent of a particular shader program but global
  52505. const bindingPointIndex = allocateBindingPointIndex();
  52506. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  52507. const buffer = gl.createBuffer();
  52508. const size = uniformsGroup.__size;
  52509. const usage = uniformsGroup.usage;
  52510. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52511. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  52512. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52513. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  52514. return buffer;
  52515. }
  52516. function allocateBindingPointIndex() {
  52517. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  52518. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  52519. allocatedBindingPoints.push( i );
  52520. return i;
  52521. }
  52522. }
  52523. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  52524. return 0;
  52525. }
  52526. function updateBufferData( uniformsGroup ) {
  52527. const buffer = buffers[ uniformsGroup.id ];
  52528. const uniforms = uniformsGroup.uniforms;
  52529. const cache = uniformsGroup.__cache;
  52530. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52531. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  52532. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52533. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52534. const uniform = uniformArray[ j ];
  52535. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  52536. const offset = uniform.__offset;
  52537. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52538. let arrayOffset = 0;
  52539. for ( let k = 0; k < values.length; k ++ ) {
  52540. const value = values[ k ];
  52541. const info = getUniformSize( value );
  52542. // TODO add integer and struct support
  52543. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52544. uniform.__data[ 0 ] = value;
  52545. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  52546. } else if ( value.isMatrix3 ) {
  52547. // manually converting 3x3 to 3x4
  52548. uniform.__data[ 0 ] = value.elements[ 0 ];
  52549. uniform.__data[ 1 ] = value.elements[ 1 ];
  52550. uniform.__data[ 2 ] = value.elements[ 2 ];
  52551. uniform.__data[ 3 ] = 0;
  52552. uniform.__data[ 4 ] = value.elements[ 3 ];
  52553. uniform.__data[ 5 ] = value.elements[ 4 ];
  52554. uniform.__data[ 6 ] = value.elements[ 5 ];
  52555. uniform.__data[ 7 ] = 0;
  52556. uniform.__data[ 8 ] = value.elements[ 6 ];
  52557. uniform.__data[ 9 ] = value.elements[ 7 ];
  52558. uniform.__data[ 10 ] = value.elements[ 8 ];
  52559. uniform.__data[ 11 ] = 0;
  52560. } else {
  52561. value.toArray( uniform.__data, arrayOffset );
  52562. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  52563. }
  52564. }
  52565. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  52566. }
  52567. }
  52568. }
  52569. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52570. }
  52571. function hasUniformChanged( uniform, index, indexArray, cache ) {
  52572. const value = uniform.value;
  52573. const indexString = index + '_' + indexArray;
  52574. if ( cache[ indexString ] === undefined ) {
  52575. // cache entry does not exist so far
  52576. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52577. cache[ indexString ] = value;
  52578. } else {
  52579. cache[ indexString ] = value.clone();
  52580. }
  52581. return true;
  52582. } else {
  52583. const cachedObject = cache[ indexString ];
  52584. // compare current value with cached entry
  52585. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52586. if ( cachedObject !== value ) {
  52587. cache[ indexString ] = value;
  52588. return true;
  52589. }
  52590. } else {
  52591. if ( cachedObject.equals( value ) === false ) {
  52592. cachedObject.copy( value );
  52593. return true;
  52594. }
  52595. }
  52596. }
  52597. return false;
  52598. }
  52599. function prepareUniformsGroup( uniformsGroup ) {
  52600. // determine total buffer size according to the STD140 layout
  52601. // Hint: STD140 is the only supported layout in WebGL 2
  52602. const uniforms = uniformsGroup.uniforms;
  52603. let offset = 0; // global buffer offset in bytes
  52604. const chunkSize = 16; // size of a chunk in bytes
  52605. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52606. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52607. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52608. const uniform = uniformArray[ j ];
  52609. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52610. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52611. const value = values[ k ];
  52612. const info = getUniformSize( value );
  52613. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52614. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52615. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52616. offset += chunkPadding;
  52617. // Check for chunk overflow
  52618. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52619. // Add padding and adjust offset
  52620. offset += ( chunkSize - chunkStart );
  52621. }
  52622. // the following two properties will be used for partial buffer updates
  52623. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52624. uniform.__offset = offset;
  52625. // Update the global offset
  52626. offset += info.storage;
  52627. }
  52628. }
  52629. }
  52630. // ensure correct final padding
  52631. const chunkOffset = offset % chunkSize;
  52632. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52633. //
  52634. uniformsGroup.__size = offset;
  52635. uniformsGroup.__cache = {};
  52636. return this;
  52637. }
  52638. function getUniformSize( value ) {
  52639. const info = {
  52640. boundary: 0, // bytes
  52641. storage: 0 // bytes
  52642. };
  52643. // determine sizes according to STD140
  52644. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52645. // float/int/bool
  52646. info.boundary = 4;
  52647. info.storage = 4;
  52648. } else if ( value.isVector2 ) {
  52649. // vec2
  52650. info.boundary = 8;
  52651. info.storage = 8;
  52652. } else if ( value.isVector3 || value.isColor ) {
  52653. // vec3
  52654. info.boundary = 16;
  52655. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52656. } else if ( value.isVector4 ) {
  52657. // vec4
  52658. info.boundary = 16;
  52659. info.storage = 16;
  52660. } else if ( value.isMatrix3 ) {
  52661. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52662. info.boundary = 48;
  52663. info.storage = 48;
  52664. } else if ( value.isMatrix4 ) {
  52665. // mat4
  52666. info.boundary = 64;
  52667. info.storage = 64;
  52668. } else if ( value.isTexture ) {
  52669. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52670. } else {
  52671. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52672. }
  52673. return info;
  52674. }
  52675. function onUniformsGroupsDispose( event ) {
  52676. const uniformsGroup = event.target;
  52677. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52678. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52679. allocatedBindingPoints.splice( index, 1 );
  52680. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52681. delete buffers[ uniformsGroup.id ];
  52682. delete updateList[ uniformsGroup.id ];
  52683. }
  52684. function dispose() {
  52685. for ( const id in buffers ) {
  52686. gl.deleteBuffer( buffers[ id ] );
  52687. }
  52688. allocatedBindingPoints = [];
  52689. buffers = {};
  52690. updateList = {};
  52691. }
  52692. return {
  52693. bind: bind,
  52694. update: update,
  52695. dispose: dispose
  52696. };
  52697. }
  52698. /**
  52699. * Precomputed DFG LUT for Image-Based Lighting
  52700. * Resolution: 16x16
  52701. * Samples: 4096 per texel
  52702. * Format: RG16F (2 half floats per texel: scale, bias)
  52703. */
  52704. const DATA = new Uint16Array( [
  52705. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  52706. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  52707. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  52708. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  52709. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  52710. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  52711. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  52712. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  52713. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  52714. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  52715. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  52716. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  52717. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  52718. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  52719. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  52720. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  52721. ] );
  52722. let lut = null;
  52723. function getDFGLUT() {
  52724. if ( lut === null ) {
  52725. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  52726. lut.name = 'DFG_LUT';
  52727. lut.minFilter = LinearFilter;
  52728. lut.magFilter = LinearFilter;
  52729. lut.wrapS = ClampToEdgeWrapping;
  52730. lut.wrapT = ClampToEdgeWrapping;
  52731. lut.generateMipmaps = false;
  52732. lut.needsUpdate = true;
  52733. }
  52734. return lut;
  52735. }
  52736. /**
  52737. * This renderer uses WebGL 2 to display scenes.
  52738. *
  52739. * WebGL 1 is not supported since `r163`.
  52740. */
  52741. class WebGLRenderer {
  52742. /**
  52743. * Constructs a new WebGL renderer.
  52744. *
  52745. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52746. */
  52747. constructor( parameters = {} ) {
  52748. const {
  52749. canvas = createCanvasElement(),
  52750. context = null,
  52751. depth = true,
  52752. stencil = false,
  52753. alpha = false,
  52754. antialias = false,
  52755. premultipliedAlpha = true,
  52756. preserveDrawingBuffer = false,
  52757. powerPreference = 'default',
  52758. failIfMajorPerformanceCaveat = false,
  52759. reversedDepthBuffer = false,
  52760. outputBufferType = UnsignedByteType,
  52761. } = parameters;
  52762. /**
  52763. * This flag can be used for type testing.
  52764. *
  52765. * @type {boolean}
  52766. * @readonly
  52767. * @default true
  52768. */
  52769. this.isWebGLRenderer = true;
  52770. let _alpha;
  52771. if ( context !== null ) {
  52772. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52773. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52774. }
  52775. _alpha = context.getContextAttributes().alpha;
  52776. } else {
  52777. _alpha = alpha;
  52778. }
  52779. const _outputBufferType = outputBufferType;
  52780. const INTEGER_FORMATS = new Set( [
  52781. RGBAIntegerFormat,
  52782. RGIntegerFormat,
  52783. RedIntegerFormat
  52784. ] );
  52785. const UNSIGNED_TYPES = new Set( [
  52786. UnsignedByteType,
  52787. UnsignedIntType,
  52788. UnsignedShortType,
  52789. UnsignedInt248Type,
  52790. UnsignedShort4444Type,
  52791. UnsignedShort5551Type
  52792. ] );
  52793. const uintClearColor = new Uint32Array( 4 );
  52794. const intClearColor = new Int32Array( 4 );
  52795. let currentRenderList = null;
  52796. let currentRenderState = null;
  52797. // render() can be called from within a callback triggered by another render.
  52798. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52799. const renderListStack = [];
  52800. const renderStateStack = [];
  52801. // internal render target for non-UnsignedByteType color buffer
  52802. let output = null;
  52803. // public properties
  52804. /**
  52805. * A canvas where the renderer draws its output. This is automatically created by the renderer
  52806. * in the constructor (if not provided already); you just need to add it to your page like so:
  52807. * ```js
  52808. * document.body.appendChild( renderer.domElement );
  52809. * ```
  52810. *
  52811. * @type {HTMLCanvasElement|OffscreenCanvas}
  52812. */
  52813. this.domElement = canvas;
  52814. /**
  52815. * A object with debug configuration settings.
  52816. *
  52817. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52818. * checked for errors during compilation and linkage process. It may be useful to disable
  52819. * this check in production for performance gain. It is strongly recommended to keep these
  52820. * checks enabled during development. If the shader does not compile and link, it will not
  52821. * work and associated material will not render.
  52822. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52823. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52824. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52825. * Assigning a custom function disables the default error reporting.
  52826. *
  52827. * @type {Object}
  52828. */
  52829. this.debug = {
  52830. /**
  52831. * Enables error checking and reporting when shader programs are being compiled.
  52832. * @type {boolean}
  52833. */
  52834. checkShaderErrors: true,
  52835. /**
  52836. * Callback for custom error reporting.
  52837. * @type {?Function}
  52838. */
  52839. onShaderError: null
  52840. };
  52841. // clearing
  52842. /**
  52843. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52844. *
  52845. * @type {boolean}
  52846. * @default true
  52847. */
  52848. this.autoClear = true;
  52849. /**
  52850. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52851. * the color buffer or not.
  52852. *
  52853. * @type {boolean}
  52854. * @default true
  52855. */
  52856. this.autoClearColor = true;
  52857. /**
  52858. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52859. * the depth buffer or not.
  52860. *
  52861. * @type {boolean}
  52862. * @default true
  52863. */
  52864. this.autoClearDepth = true;
  52865. /**
  52866. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52867. * the stencil buffer or not.
  52868. *
  52869. * @type {boolean}
  52870. * @default true
  52871. */
  52872. this.autoClearStencil = true;
  52873. // scene graph
  52874. /**
  52875. * Whether the renderer should sort objects or not.
  52876. *
  52877. * Note: Sorting is used to attempt to properly render objects that have some
  52878. * degree of transparency. By definition, sorting objects may not work in all
  52879. * cases. Depending on the needs of application, it may be necessary to turn
  52880. * off sorting and use other methods to deal with transparency rendering e.g.
  52881. * manually determining each object's rendering order.
  52882. *
  52883. * @type {boolean}
  52884. * @default true
  52885. */
  52886. this.sortObjects = true;
  52887. // user-defined clipping
  52888. /**
  52889. * User-defined clipping planes specified in world space. These planes apply globally.
  52890. * Points in space whose dot product with the plane is negative are cut away.
  52891. *
  52892. * @type {Array<Plane>}
  52893. */
  52894. this.clippingPlanes = [];
  52895. /**
  52896. * Whether the renderer respects object-level clipping planes or not.
  52897. *
  52898. * @type {boolean}
  52899. * @default false
  52900. */
  52901. this.localClippingEnabled = false;
  52902. // tone mapping
  52903. /**
  52904. * The tone mapping technique of the renderer.
  52905. *
  52906. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52907. * @default NoToneMapping
  52908. */
  52909. this.toneMapping = NoToneMapping;
  52910. /**
  52911. * Exposure level of tone mapping.
  52912. *
  52913. * @type {number}
  52914. * @default 1
  52915. */
  52916. this.toneMappingExposure = 1.0;
  52917. // transmission
  52918. /**
  52919. * The normalized resolution scale for the transmission render target, measured in percentage
  52920. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52921. * when using {@link MeshPhysicalMaterial#transmission}.
  52922. *
  52923. * @type {number}
  52924. * @default 1
  52925. */
  52926. this.transmissionResolutionScale = 1.0;
  52927. // internal properties
  52928. const _this = this;
  52929. let _isContextLost = false;
  52930. // internal state cache
  52931. this._outputColorSpace = SRGBColorSpace;
  52932. let _currentActiveCubeFace = 0;
  52933. let _currentActiveMipmapLevel = 0;
  52934. let _currentRenderTarget = null;
  52935. let _currentMaterialId = -1;
  52936. let _currentCamera = null;
  52937. const _currentViewport = new Vector4();
  52938. const _currentScissor = new Vector4();
  52939. let _currentScissorTest = null;
  52940. const _currentClearColor = new Color( 0x000000 );
  52941. let _currentClearAlpha = 0;
  52942. //
  52943. let _width = canvas.width;
  52944. let _height = canvas.height;
  52945. let _pixelRatio = 1;
  52946. let _opaqueSort = null;
  52947. let _transparentSort = null;
  52948. const _viewport = new Vector4( 0, 0, _width, _height );
  52949. const _scissor = new Vector4( 0, 0, _width, _height );
  52950. let _scissorTest = false;
  52951. // frustum
  52952. const _frustum = new Frustum();
  52953. // clipping
  52954. let _clippingEnabled = false;
  52955. let _localClippingEnabled = false;
  52956. // camera matrices cache
  52957. const _projScreenMatrix = new Matrix4();
  52958. const _vector3 = new Vector3();
  52959. const _vector4 = new Vector4();
  52960. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  52961. let _renderBackground = false;
  52962. function getTargetPixelRatio() {
  52963. return _currentRenderTarget === null ? _pixelRatio : 1;
  52964. }
  52965. // initialize
  52966. let _gl = context;
  52967. function getContext( contextName, contextAttributes ) {
  52968. return canvas.getContext( contextName, contextAttributes );
  52969. }
  52970. try {
  52971. const contextAttributes = {
  52972. alpha: true,
  52973. depth,
  52974. stencil,
  52975. antialias,
  52976. premultipliedAlpha,
  52977. preserveDrawingBuffer,
  52978. powerPreference,
  52979. failIfMajorPerformanceCaveat,
  52980. };
  52981. // OffscreenCanvas does not have setAttribute, see #22811
  52982. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  52983. // event listeners must be registered before WebGL context is created, see #12753
  52984. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  52985. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  52986. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52987. if ( _gl === null ) {
  52988. const contextName = 'webgl2';
  52989. _gl = getContext( contextName, contextAttributes );
  52990. if ( _gl === null ) {
  52991. if ( getContext( contextName ) ) {
  52992. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  52993. } else {
  52994. throw new Error( 'Error creating WebGL context.' );
  52995. }
  52996. }
  52997. }
  52998. } catch ( e ) {
  52999. error( 'WebGLRenderer: ' + e.message );
  53000. throw e;
  53001. }
  53002. let extensions, capabilities, state, info;
  53003. let properties, textures, environments, attributes, geometries, objects;
  53004. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  53005. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  53006. let utils, bindingStates, uniformsGroups;
  53007. function initGLContext() {
  53008. extensions = new WebGLExtensions( _gl );
  53009. extensions.init();
  53010. utils = new WebGLUtils( _gl, extensions );
  53011. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  53012. state = new WebGLState( _gl, extensions );
  53013. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  53014. state.buffers.depth.setReversed( true );
  53015. }
  53016. info = new WebGLInfo( _gl );
  53017. properties = new WebGLProperties();
  53018. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  53019. environments = new WebGLEnvironments( _this );
  53020. attributes = new WebGLAttributes( _gl );
  53021. bindingStates = new WebGLBindingStates( _gl, attributes );
  53022. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  53023. objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info );
  53024. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  53025. clipping = new WebGLClipping( properties );
  53026. programCache = new WebGLPrograms( _this, environments, extensions, capabilities, bindingStates, clipping );
  53027. materials = new WebGLMaterials( _this, properties );
  53028. renderLists = new WebGLRenderLists();
  53029. renderStates = new WebGLRenderStates( extensions );
  53030. background = new WebGLBackground( _this, environments, state, objects, _alpha, premultipliedAlpha );
  53031. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  53032. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  53033. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  53034. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  53035. info.programs = programCache.programs;
  53036. /**
  53037. * Holds details about the capabilities of the current rendering context.
  53038. *
  53039. * @name WebGLRenderer#capabilities
  53040. * @type {WebGLRenderer~Capabilities}
  53041. */
  53042. _this.capabilities = capabilities;
  53043. /**
  53044. * Provides methods for retrieving and testing WebGL extensions.
  53045. *
  53046. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  53047. * and return the extension object if available.
  53048. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  53049. *
  53050. * @name WebGLRenderer#extensions
  53051. * @type {Object}
  53052. */
  53053. _this.extensions = extensions;
  53054. /**
  53055. * Used to track properties of other objects like native WebGL objects.
  53056. *
  53057. * @name WebGLRenderer#properties
  53058. * @type {Object}
  53059. */
  53060. _this.properties = properties;
  53061. /**
  53062. * Manages the render lists of the renderer.
  53063. *
  53064. * @name WebGLRenderer#renderLists
  53065. * @type {Object}
  53066. */
  53067. _this.renderLists = renderLists;
  53068. /**
  53069. * Interface for managing shadows.
  53070. *
  53071. * @name WebGLRenderer#shadowMap
  53072. * @type {WebGLRenderer~ShadowMap}
  53073. */
  53074. _this.shadowMap = shadowMap;
  53075. /**
  53076. * Interface for managing the WebGL state.
  53077. *
  53078. * @name WebGLRenderer#state
  53079. * @type {Object}
  53080. */
  53081. _this.state = state;
  53082. /**
  53083. * Holds a series of statistical information about the GPU memory
  53084. * and the rendering process. Useful for debugging and monitoring.
  53085. *
  53086. * By default these data are reset at each render call but when having
  53087. * multiple render passes per frame (e.g. when using post processing) it can
  53088. * be preferred to reset with a custom pattern. First, set `autoReset` to
  53089. * `false`.
  53090. * ```js
  53091. * renderer.info.autoReset = false;
  53092. * ```
  53093. * Call `reset()` whenever you have finished to render a single frame.
  53094. * ```js
  53095. * renderer.info.reset();
  53096. * ```
  53097. *
  53098. * @name WebGLRenderer#info
  53099. * @type {WebGLRenderer~Info}
  53100. */
  53101. _this.info = info;
  53102. }
  53103. initGLContext();
  53104. // initialize internal render target for non-UnsignedByteType color buffer
  53105. if ( _outputBufferType !== UnsignedByteType ) {
  53106. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  53107. }
  53108. // xr
  53109. const xr = new WebXRManager( _this, _gl );
  53110. /**
  53111. * A reference to the XR manager.
  53112. *
  53113. * @type {WebXRManager}
  53114. */
  53115. this.xr = xr;
  53116. /**
  53117. * Returns the rendering context.
  53118. *
  53119. * @return {WebGL2RenderingContext} The rendering context.
  53120. */
  53121. this.getContext = function () {
  53122. return _gl;
  53123. };
  53124. /**
  53125. * Returns the rendering context attributes.
  53126. *
  53127. * @return {WebGLContextAttributes} The rendering context attributes.
  53128. */
  53129. this.getContextAttributes = function () {
  53130. return _gl.getContextAttributes();
  53131. };
  53132. /**
  53133. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  53134. */
  53135. this.forceContextLoss = function () {
  53136. const extension = extensions.get( 'WEBGL_lose_context' );
  53137. if ( extension ) extension.loseContext();
  53138. };
  53139. /**
  53140. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  53141. */
  53142. this.forceContextRestore = function () {
  53143. const extension = extensions.get( 'WEBGL_lose_context' );
  53144. if ( extension ) extension.restoreContext();
  53145. };
  53146. /**
  53147. * Returns the pixel ratio.
  53148. *
  53149. * @return {number} The pixel ratio.
  53150. */
  53151. this.getPixelRatio = function () {
  53152. return _pixelRatio;
  53153. };
  53154. /**
  53155. * Sets the given pixel ratio and resizes the canvas if necessary.
  53156. *
  53157. * @param {number} value - The pixel ratio.
  53158. */
  53159. this.setPixelRatio = function ( value ) {
  53160. if ( value === undefined ) return;
  53161. _pixelRatio = value;
  53162. this.setSize( _width, _height, false );
  53163. };
  53164. /**
  53165. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  53166. *
  53167. * @param {Vector2} target - The method writes the result in this target object.
  53168. * @return {Vector2} The renderer's size in logical pixels.
  53169. */
  53170. this.getSize = function ( target ) {
  53171. return target.set( _width, _height );
  53172. };
  53173. /**
  53174. * Resizes the output canvas to (width, height) with device pixel ratio taken
  53175. * into account, and also sets the viewport to fit that size, starting in (0,
  53176. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  53177. *
  53178. * @param {number} width - The width in logical pixels.
  53179. * @param {number} height - The height in logical pixels.
  53180. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  53181. */
  53182. this.setSize = function ( width, height, updateStyle = true ) {
  53183. if ( xr.isPresenting ) {
  53184. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  53185. return;
  53186. }
  53187. _width = width;
  53188. _height = height;
  53189. canvas.width = Math.floor( width * _pixelRatio );
  53190. canvas.height = Math.floor( height * _pixelRatio );
  53191. if ( updateStyle === true ) {
  53192. canvas.style.width = width + 'px';
  53193. canvas.style.height = height + 'px';
  53194. }
  53195. if ( output !== null ) {
  53196. output.setSize( canvas.width, canvas.height );
  53197. }
  53198. this.setViewport( 0, 0, width, height );
  53199. };
  53200. /**
  53201. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  53202. *
  53203. * @param {Vector2} target - The method writes the result in this target object.
  53204. * @return {Vector2} The drawing buffer size.
  53205. */
  53206. this.getDrawingBufferSize = function ( target ) {
  53207. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  53208. };
  53209. /**
  53210. * This method allows to define the drawing buffer size by specifying
  53211. * width, height and pixel ratio all at once. The size of the drawing
  53212. * buffer is computed with this formula:
  53213. * ```js
  53214. * size.x = width * pixelRatio;
  53215. * size.y = height * pixelRatio;
  53216. * ```
  53217. *
  53218. * @param {number} width - The width in logical pixels.
  53219. * @param {number} height - The height in logical pixels.
  53220. * @param {number} pixelRatio - The pixel ratio.
  53221. */
  53222. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  53223. _width = width;
  53224. _height = height;
  53225. _pixelRatio = pixelRatio;
  53226. canvas.width = Math.floor( width * pixelRatio );
  53227. canvas.height = Math.floor( height * pixelRatio );
  53228. this.setViewport( 0, 0, width, height );
  53229. };
  53230. /**
  53231. * Sets the post-processing effects to be applied after rendering.
  53232. *
  53233. * @param {Array} effects - An array of post-processing effects.
  53234. */
  53235. this.setEffects = function ( effects ) {
  53236. if ( _outputBufferType === UnsignedByteType ) {
  53237. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  53238. return;
  53239. }
  53240. if ( effects ) {
  53241. for ( let i = 0; i < effects.length; i ++ ) {
  53242. if ( effects[ i ].isOutputPass === true ) {
  53243. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  53244. break;
  53245. }
  53246. }
  53247. }
  53248. output.setEffects( effects || [] );
  53249. };
  53250. /**
  53251. * Returns the current viewport definition.
  53252. *
  53253. * @param {Vector2} target - The method writes the result in this target object.
  53254. * @return {Vector2} The current viewport definition.
  53255. */
  53256. this.getCurrentViewport = function ( target ) {
  53257. return target.copy( _currentViewport );
  53258. };
  53259. /**
  53260. * Returns the viewport definition.
  53261. *
  53262. * @param {Vector4} target - The method writes the result in this target object.
  53263. * @return {Vector4} The viewport definition.
  53264. */
  53265. this.getViewport = function ( target ) {
  53266. return target.copy( _viewport );
  53267. };
  53268. /**
  53269. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  53270. *
  53271. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  53272. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  53273. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  53274. * @param {number} width - The width of the viewport in logical pixel unit.
  53275. * @param {number} height - The height of the viewport in logical pixel unit.
  53276. */
  53277. this.setViewport = function ( x, y, width, height ) {
  53278. if ( x.isVector4 ) {
  53279. _viewport.set( x.x, x.y, x.z, x.w );
  53280. } else {
  53281. _viewport.set( x, y, width, height );
  53282. }
  53283. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  53284. };
  53285. /**
  53286. * Returns the scissor region.
  53287. *
  53288. * @param {Vector4} target - The method writes the result in this target object.
  53289. * @return {Vector4} The scissor region.
  53290. */
  53291. this.getScissor = function ( target ) {
  53292. return target.copy( _scissor );
  53293. };
  53294. /**
  53295. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  53296. *
  53297. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  53298. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  53299. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  53300. * @param {number} width - The width of the scissor region in logical pixel unit.
  53301. * @param {number} height - The height of the scissor region in logical pixel unit.
  53302. */
  53303. this.setScissor = function ( x, y, width, height ) {
  53304. if ( x.isVector4 ) {
  53305. _scissor.set( x.x, x.y, x.z, x.w );
  53306. } else {
  53307. _scissor.set( x, y, width, height );
  53308. }
  53309. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  53310. };
  53311. /**
  53312. * Returns `true` if the scissor test is enabled.
  53313. *
  53314. * @return {boolean} Whether the scissor test is enabled or not.
  53315. */
  53316. this.getScissorTest = function () {
  53317. return _scissorTest;
  53318. };
  53319. /**
  53320. * Enable or disable the scissor test. When this is enabled, only the pixels
  53321. * within the defined scissor area will be affected by further renderer
  53322. * actions.
  53323. *
  53324. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  53325. */
  53326. this.setScissorTest = function ( boolean ) {
  53327. state.setScissorTest( _scissorTest = boolean );
  53328. };
  53329. /**
  53330. * Sets a custom opaque sort function for the render lists. Pass `null`
  53331. * to use the default `painterSortStable` function.
  53332. *
  53333. * @param {?Function} method - The opaque sort function.
  53334. */
  53335. this.setOpaqueSort = function ( method ) {
  53336. _opaqueSort = method;
  53337. };
  53338. /**
  53339. * Sets a custom transparent sort function for the render lists. Pass `null`
  53340. * to use the default `reversePainterSortStable` function.
  53341. *
  53342. * @param {?Function} method - The opaque sort function.
  53343. */
  53344. this.setTransparentSort = function ( method ) {
  53345. _transparentSort = method;
  53346. };
  53347. // Clearing
  53348. /**
  53349. * Returns the clear color.
  53350. *
  53351. * @param {Color} target - The method writes the result in this target object.
  53352. * @return {Color} The clear color.
  53353. */
  53354. this.getClearColor = function ( target ) {
  53355. return target.copy( background.getClearColor() );
  53356. };
  53357. /**
  53358. * Sets the clear color and alpha.
  53359. *
  53360. * @param {Color} color - The clear color.
  53361. * @param {number} [alpha=1] - The clear alpha.
  53362. */
  53363. this.setClearColor = function () {
  53364. background.setClearColor( ...arguments );
  53365. };
  53366. /**
  53367. * Returns the clear alpha. Ranges within `[0,1]`.
  53368. *
  53369. * @return {number} The clear alpha.
  53370. */
  53371. this.getClearAlpha = function () {
  53372. return background.getClearAlpha();
  53373. };
  53374. /**
  53375. * Sets the clear alpha.
  53376. *
  53377. * @param {number} alpha - The clear alpha.
  53378. */
  53379. this.setClearAlpha = function () {
  53380. background.setClearAlpha( ...arguments );
  53381. };
  53382. /**
  53383. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  53384. * This method initializes the buffers to the current clear color values.
  53385. *
  53386. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  53387. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  53388. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  53389. */
  53390. this.clear = function ( color = true, depth = true, stencil = true ) {
  53391. let bits = 0;
  53392. if ( color ) {
  53393. // check if we're trying to clear an integer target
  53394. let isIntegerFormat = false;
  53395. if ( _currentRenderTarget !== null ) {
  53396. const targetFormat = _currentRenderTarget.texture.format;
  53397. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  53398. }
  53399. // use the appropriate clear functions to clear the target if it's a signed
  53400. // or unsigned integer target
  53401. if ( isIntegerFormat ) {
  53402. const targetType = _currentRenderTarget.texture.type;
  53403. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  53404. const clearColor = background.getClearColor();
  53405. const a = background.getClearAlpha();
  53406. const r = clearColor.r;
  53407. const g = clearColor.g;
  53408. const b = clearColor.b;
  53409. if ( isUnsignedType ) {
  53410. uintClearColor[ 0 ] = r;
  53411. uintClearColor[ 1 ] = g;
  53412. uintClearColor[ 2 ] = b;
  53413. uintClearColor[ 3 ] = a;
  53414. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  53415. } else {
  53416. intClearColor[ 0 ] = r;
  53417. intClearColor[ 1 ] = g;
  53418. intClearColor[ 2 ] = b;
  53419. intClearColor[ 3 ] = a;
  53420. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  53421. }
  53422. } else {
  53423. bits |= _gl.COLOR_BUFFER_BIT;
  53424. }
  53425. }
  53426. if ( depth ) {
  53427. bits |= _gl.DEPTH_BUFFER_BIT;
  53428. }
  53429. if ( stencil ) {
  53430. bits |= _gl.STENCIL_BUFFER_BIT;
  53431. this.state.buffers.stencil.setMask( 0xffffffff );
  53432. }
  53433. _gl.clear( bits );
  53434. };
  53435. /**
  53436. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  53437. */
  53438. this.clearColor = function () {
  53439. this.clear( true, false, false );
  53440. };
  53441. /**
  53442. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  53443. */
  53444. this.clearDepth = function () {
  53445. this.clear( false, true, false );
  53446. };
  53447. /**
  53448. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  53449. */
  53450. this.clearStencil = function () {
  53451. this.clear( false, false, true );
  53452. };
  53453. /**
  53454. * Frees the GPU-related resources allocated by this instance. Call this
  53455. * method whenever this instance is no longer used in your app.
  53456. */
  53457. this.dispose = function () {
  53458. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  53459. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  53460. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53461. background.dispose();
  53462. renderLists.dispose();
  53463. renderStates.dispose();
  53464. properties.dispose();
  53465. environments.dispose();
  53466. objects.dispose();
  53467. bindingStates.dispose();
  53468. uniformsGroups.dispose();
  53469. programCache.dispose();
  53470. xr.dispose();
  53471. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  53472. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  53473. animation.stop();
  53474. };
  53475. // Events
  53476. function onContextLost( event ) {
  53477. event.preventDefault();
  53478. log( 'WebGLRenderer: Context Lost.' );
  53479. _isContextLost = true;
  53480. }
  53481. function onContextRestore( /* event */ ) {
  53482. log( 'WebGLRenderer: Context Restored.' );
  53483. _isContextLost = false;
  53484. const infoAutoReset = info.autoReset;
  53485. const shadowMapEnabled = shadowMap.enabled;
  53486. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  53487. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  53488. const shadowMapType = shadowMap.type;
  53489. initGLContext();
  53490. info.autoReset = infoAutoReset;
  53491. shadowMap.enabled = shadowMapEnabled;
  53492. shadowMap.autoUpdate = shadowMapAutoUpdate;
  53493. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  53494. shadowMap.type = shadowMapType;
  53495. }
  53496. function onContextCreationError( event ) {
  53497. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  53498. }
  53499. function onMaterialDispose( event ) {
  53500. const material = event.target;
  53501. material.removeEventListener( 'dispose', onMaterialDispose );
  53502. deallocateMaterial( material );
  53503. }
  53504. // Buffer deallocation
  53505. function deallocateMaterial( material ) {
  53506. releaseMaterialProgramReferences( material );
  53507. properties.remove( material );
  53508. }
  53509. function releaseMaterialProgramReferences( material ) {
  53510. const programs = properties.get( material ).programs;
  53511. if ( programs !== undefined ) {
  53512. programs.forEach( function ( program ) {
  53513. programCache.releaseProgram( program );
  53514. } );
  53515. if ( material.isShaderMaterial ) {
  53516. programCache.releaseShaderCache( material );
  53517. }
  53518. }
  53519. }
  53520. // Buffer rendering
  53521. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  53522. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  53523. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53524. const program = setProgram( camera, scene, geometry, material, object );
  53525. state.setMaterial( material, frontFaceCW );
  53526. //
  53527. let index = geometry.index;
  53528. let rangeFactor = 1;
  53529. if ( material.wireframe === true ) {
  53530. index = geometries.getWireframeAttribute( geometry );
  53531. if ( index === undefined ) return;
  53532. rangeFactor = 2;
  53533. }
  53534. //
  53535. const drawRange = geometry.drawRange;
  53536. const position = geometry.attributes.position;
  53537. let drawStart = drawRange.start * rangeFactor;
  53538. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  53539. if ( group !== null ) {
  53540. drawStart = Math.max( drawStart, group.start * rangeFactor );
  53541. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  53542. }
  53543. if ( index !== null ) {
  53544. drawStart = Math.max( drawStart, 0 );
  53545. drawEnd = Math.min( drawEnd, index.count );
  53546. } else if ( position !== undefined && position !== null ) {
  53547. drawStart = Math.max( drawStart, 0 );
  53548. drawEnd = Math.min( drawEnd, position.count );
  53549. }
  53550. const drawCount = drawEnd - drawStart;
  53551. if ( drawCount < 0 || drawCount === Infinity ) return;
  53552. //
  53553. bindingStates.setup( object, material, program, geometry, index );
  53554. let attribute;
  53555. let renderer = bufferRenderer;
  53556. if ( index !== null ) {
  53557. attribute = attributes.get( index );
  53558. renderer = indexedBufferRenderer;
  53559. renderer.setIndex( attribute );
  53560. }
  53561. //
  53562. if ( object.isMesh ) {
  53563. if ( material.wireframe === true ) {
  53564. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  53565. renderer.setMode( _gl.LINES );
  53566. } else {
  53567. renderer.setMode( _gl.TRIANGLES );
  53568. }
  53569. } else if ( object.isLine ) {
  53570. let lineWidth = material.linewidth;
  53571. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  53572. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  53573. if ( object.isLineSegments ) {
  53574. renderer.setMode( _gl.LINES );
  53575. } else if ( object.isLineLoop ) {
  53576. renderer.setMode( _gl.LINE_LOOP );
  53577. } else {
  53578. renderer.setMode( _gl.LINE_STRIP );
  53579. }
  53580. } else if ( object.isPoints ) {
  53581. renderer.setMode( _gl.POINTS );
  53582. } else if ( object.isSprite ) {
  53583. renderer.setMode( _gl.TRIANGLES );
  53584. }
  53585. if ( object.isBatchedMesh ) {
  53586. if ( object._multiDrawInstances !== null ) {
  53587. // @deprecated, r174
  53588. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53589. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  53590. } else {
  53591. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  53592. const starts = object._multiDrawStarts;
  53593. const counts = object._multiDrawCounts;
  53594. const drawCount = object._multiDrawCount;
  53595. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  53596. const uniforms = properties.get( material ).currentProgram.getUniforms();
  53597. for ( let i = 0; i < drawCount; i ++ ) {
  53598. uniforms.setValue( _gl, '_gl_DrawID', i );
  53599. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  53600. }
  53601. } else {
  53602. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  53603. }
  53604. }
  53605. } else if ( object.isInstancedMesh ) {
  53606. renderer.renderInstances( drawStart, drawCount, object.count );
  53607. } else if ( geometry.isInstancedBufferGeometry ) {
  53608. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  53609. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  53610. renderer.renderInstances( drawStart, drawCount, instanceCount );
  53611. } else {
  53612. renderer.render( drawStart, drawCount );
  53613. }
  53614. };
  53615. // Compile
  53616. function prepareMaterial( material, scene, object ) {
  53617. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53618. material.side = BackSide;
  53619. material.needsUpdate = true;
  53620. getProgram( material, scene, object );
  53621. material.side = FrontSide;
  53622. material.needsUpdate = true;
  53623. getProgram( material, scene, object );
  53624. material.side = DoubleSide;
  53625. } else {
  53626. getProgram( material, scene, object );
  53627. }
  53628. }
  53629. /**
  53630. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53631. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53632. * optional parameter for applying the target scene.
  53633. *
  53634. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53635. *
  53636. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53637. * @param {Camera} camera - The camera.
  53638. * @param {?Scene} [targetScene=null] - The target scene.
  53639. * @return {Set<Material>} The precompiled materials.
  53640. */
  53641. this.compile = function ( scene, camera, targetScene = null ) {
  53642. if ( targetScene === null ) targetScene = scene;
  53643. currentRenderState = renderStates.get( targetScene );
  53644. currentRenderState.init( camera );
  53645. renderStateStack.push( currentRenderState );
  53646. // gather lights from both the target scene and the new object that will be added to the scene.
  53647. targetScene.traverseVisible( function ( object ) {
  53648. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53649. currentRenderState.pushLight( object );
  53650. if ( object.castShadow ) {
  53651. currentRenderState.pushShadow( object );
  53652. }
  53653. }
  53654. } );
  53655. if ( scene !== targetScene ) {
  53656. scene.traverseVisible( function ( object ) {
  53657. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53658. currentRenderState.pushLight( object );
  53659. if ( object.castShadow ) {
  53660. currentRenderState.pushShadow( object );
  53661. }
  53662. }
  53663. } );
  53664. }
  53665. currentRenderState.setupLights();
  53666. // Only initialize materials in the new scene, not the targetScene.
  53667. const materials = new Set();
  53668. scene.traverse( function ( object ) {
  53669. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53670. return;
  53671. }
  53672. const material = object.material;
  53673. if ( material ) {
  53674. if ( Array.isArray( material ) ) {
  53675. for ( let i = 0; i < material.length; i ++ ) {
  53676. const material2 = material[ i ];
  53677. prepareMaterial( material2, targetScene, object );
  53678. materials.add( material2 );
  53679. }
  53680. } else {
  53681. prepareMaterial( material, targetScene, object );
  53682. materials.add( material );
  53683. }
  53684. }
  53685. } );
  53686. currentRenderState = renderStateStack.pop();
  53687. return materials;
  53688. };
  53689. // compileAsync
  53690. /**
  53691. * Asynchronous version of {@link WebGLRenderer#compile}.
  53692. *
  53693. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53694. * it is recommended to use this version of `compile()` whenever possible.
  53695. *
  53696. * @async
  53697. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53698. * @param {Camera} camera - The camera.
  53699. * @param {?Scene} [targetScene=null] - The target scene.
  53700. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53701. */
  53702. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53703. const materials = this.compile( scene, camera, targetScene );
  53704. // Wait for all the materials in the new object to indicate that they're
  53705. // ready to be used before resolving the promise.
  53706. return new Promise( ( resolve ) => {
  53707. function checkMaterialsReady() {
  53708. materials.forEach( function ( material ) {
  53709. const materialProperties = properties.get( material );
  53710. const program = materialProperties.currentProgram;
  53711. if ( program.isReady() ) {
  53712. // remove any programs that report they're ready to use from the list
  53713. materials.delete( material );
  53714. }
  53715. } );
  53716. // once the list of compiling materials is empty, call the callback
  53717. if ( materials.size === 0 ) {
  53718. resolve( scene );
  53719. return;
  53720. }
  53721. // if some materials are still not ready, wait a bit and check again
  53722. setTimeout( checkMaterialsReady, 10 );
  53723. }
  53724. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53725. // If we can check the compilation status of the materials without
  53726. // blocking then do so right away.
  53727. checkMaterialsReady();
  53728. } else {
  53729. // Otherwise start by waiting a bit to give the materials we just
  53730. // initialized a chance to finish.
  53731. setTimeout( checkMaterialsReady, 10 );
  53732. }
  53733. } );
  53734. };
  53735. // Animation Loop
  53736. let onAnimationFrameCallback = null;
  53737. function onAnimationFrame( time ) {
  53738. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53739. }
  53740. function onXRSessionStart() {
  53741. animation.stop();
  53742. }
  53743. function onXRSessionEnd() {
  53744. animation.start();
  53745. }
  53746. const animation = new WebGLAnimation();
  53747. animation.setAnimationLoop( onAnimationFrame );
  53748. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53749. /**
  53750. * Applications are advised to always define the animation loop
  53751. * with this method and not manually with `requestAnimationFrame()`
  53752. * for best compatibility.
  53753. *
  53754. * @param {?onAnimationCallback} callback - The application's animation loop.
  53755. */
  53756. this.setAnimationLoop = function ( callback ) {
  53757. onAnimationFrameCallback = callback;
  53758. xr.setAnimationLoop( callback );
  53759. ( callback === null ) ? animation.stop() : animation.start();
  53760. };
  53761. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53762. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53763. // Rendering
  53764. /**
  53765. * Renders the given scene (or other type of 3D object) using the given camera.
  53766. *
  53767. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53768. * or to the canvas as usual.
  53769. *
  53770. * By default render buffers are cleared before rendering but you can prevent
  53771. * this by setting the property `autoClear` to `false`. If you want to prevent
  53772. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53773. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53774. *
  53775. * @param {Object3D} scene - The scene to render.
  53776. * @param {Camera} camera - The camera.
  53777. */
  53778. this.render = function ( scene, camera ) {
  53779. if ( camera !== undefined && camera.isCamera !== true ) {
  53780. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53781. return;
  53782. }
  53783. if ( _isContextLost === true ) return;
  53784. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  53785. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  53786. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  53787. // update scene graph
  53788. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53789. // update camera matrices and frustum
  53790. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53791. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  53792. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53793. camera = xr.getCamera(); // use XR camera for rendering
  53794. }
  53795. //
  53796. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53797. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53798. currentRenderState.init( camera );
  53799. renderStateStack.push( currentRenderState );
  53800. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53801. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53802. _localClippingEnabled = this.localClippingEnabled;
  53803. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53804. currentRenderList = renderLists.get( scene, renderListStack.length );
  53805. currentRenderList.init();
  53806. renderListStack.push( currentRenderList );
  53807. if ( xr.enabled === true && xr.isPresenting === true ) {
  53808. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53809. if ( depthSensingMesh !== null ) {
  53810. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53811. }
  53812. }
  53813. projectObject( scene, camera, 0, _this.sortObjects );
  53814. currentRenderList.finish();
  53815. if ( _this.sortObjects === true ) {
  53816. currentRenderList.sort( _opaqueSort, _transparentSort );
  53817. }
  53818. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53819. if ( _renderBackground ) {
  53820. background.addToRenderList( currentRenderList, scene );
  53821. }
  53822. //
  53823. this.info.render.frame ++;
  53824. if ( _clippingEnabled === true ) clipping.beginShadows();
  53825. const shadowsArray = currentRenderState.state.shadowsArray;
  53826. shadowMap.render( shadowsArray, scene, camera );
  53827. if ( _clippingEnabled === true ) clipping.endShadows();
  53828. //
  53829. if ( this.info.autoReset === true ) this.info.reset();
  53830. // render scene (skip if first effect is a render pass - it will render the scene itself)
  53831. const skipSceneRender = useOutput && output.hasRenderPass();
  53832. if ( skipSceneRender === false ) {
  53833. const opaqueObjects = currentRenderList.opaque;
  53834. const transmissiveObjects = currentRenderList.transmissive;
  53835. currentRenderState.setupLights();
  53836. if ( camera.isArrayCamera ) {
  53837. const cameras = camera.cameras;
  53838. if ( transmissiveObjects.length > 0 ) {
  53839. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53840. const camera2 = cameras[ i ];
  53841. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53842. }
  53843. }
  53844. if ( _renderBackground ) background.render( scene );
  53845. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53846. const camera2 = cameras[ i ];
  53847. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53848. }
  53849. } else {
  53850. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53851. if ( _renderBackground ) background.render( scene );
  53852. renderScene( currentRenderList, scene, camera );
  53853. }
  53854. }
  53855. //
  53856. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53857. // resolve multisample renderbuffers to a single-sample texture if necessary
  53858. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53859. // Generate mipmap if we're using any kind of mipmap filtering
  53860. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53861. }
  53862. // copy from internal render target to canvas using fullscreen quad
  53863. if ( useOutput ) {
  53864. output.end( _this );
  53865. }
  53866. //
  53867. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53868. // _gl.finish();
  53869. bindingStates.resetDefaultState();
  53870. _currentMaterialId = -1;
  53871. _currentCamera = null;
  53872. renderStateStack.pop();
  53873. if ( renderStateStack.length > 0 ) {
  53874. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53875. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53876. } else {
  53877. currentRenderState = null;
  53878. }
  53879. renderListStack.pop();
  53880. if ( renderListStack.length > 0 ) {
  53881. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53882. } else {
  53883. currentRenderList = null;
  53884. }
  53885. };
  53886. function projectObject( object, camera, groupOrder, sortObjects ) {
  53887. if ( object.visible === false ) return;
  53888. const visible = object.layers.test( camera.layers );
  53889. if ( visible ) {
  53890. if ( object.isGroup ) {
  53891. groupOrder = object.renderOrder;
  53892. } else if ( object.isLOD ) {
  53893. if ( object.autoUpdate === true ) object.update( camera );
  53894. } else if ( object.isLight ) {
  53895. currentRenderState.pushLight( object );
  53896. if ( object.castShadow ) {
  53897. currentRenderState.pushShadow( object );
  53898. }
  53899. } else if ( object.isSprite ) {
  53900. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53901. if ( sortObjects ) {
  53902. _vector4.setFromMatrixPosition( object.matrixWorld )
  53903. .applyMatrix4( _projScreenMatrix );
  53904. }
  53905. const geometry = objects.update( object );
  53906. const material = object.material;
  53907. if ( material.visible ) {
  53908. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53909. }
  53910. }
  53911. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53912. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53913. const geometry = objects.update( object );
  53914. const material = object.material;
  53915. if ( sortObjects ) {
  53916. if ( object.boundingSphere !== undefined ) {
  53917. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53918. _vector4.copy( object.boundingSphere.center );
  53919. } else {
  53920. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53921. _vector4.copy( geometry.boundingSphere.center );
  53922. }
  53923. _vector4
  53924. .applyMatrix4( object.matrixWorld )
  53925. .applyMatrix4( _projScreenMatrix );
  53926. }
  53927. if ( Array.isArray( material ) ) {
  53928. const groups = geometry.groups;
  53929. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53930. const group = groups[ i ];
  53931. const groupMaterial = material[ group.materialIndex ];
  53932. if ( groupMaterial && groupMaterial.visible ) {
  53933. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  53934. }
  53935. }
  53936. } else if ( material.visible ) {
  53937. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53938. }
  53939. }
  53940. }
  53941. }
  53942. const children = object.children;
  53943. for ( let i = 0, l = children.length; i < l; i ++ ) {
  53944. projectObject( children[ i ], camera, groupOrder, sortObjects );
  53945. }
  53946. }
  53947. function renderScene( currentRenderList, scene, camera, viewport ) {
  53948. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  53949. currentRenderState.setupLightsView( camera );
  53950. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53951. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  53952. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  53953. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  53954. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  53955. // Ensure depth buffer writing is enabled so it can be cleared on next render
  53956. state.buffers.depth.setTest( true );
  53957. state.buffers.depth.setMask( true );
  53958. state.buffers.color.setMask( true );
  53959. state.setPolygonOffset( false );
  53960. }
  53961. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  53962. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53963. if ( overrideMaterial !== null ) {
  53964. return;
  53965. }
  53966. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  53967. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  53968. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  53969. generateMipmaps: true,
  53970. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  53971. minFilter: LinearMipmapLinearFilter,
  53972. samples: capabilities.samples,
  53973. stencilBuffer: stencil,
  53974. resolveDepthBuffer: false,
  53975. resolveStencilBuffer: false,
  53976. colorSpace: ColorManagement.workingColorSpace,
  53977. } );
  53978. // debug
  53979. /*
  53980. const geometry = new PlaneGeometry();
  53981. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  53982. const mesh = new Mesh( geometry, material );
  53983. scene.add( mesh );
  53984. */
  53985. }
  53986. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  53987. const activeViewport = camera.viewport || _currentViewport;
  53988. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  53989. //
  53990. const currentRenderTarget = _this.getRenderTarget();
  53991. const currentActiveCubeFace = _this.getActiveCubeFace();
  53992. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  53993. _this.setRenderTarget( transmissionRenderTarget );
  53994. _this.getClearColor( _currentClearColor );
  53995. _currentClearAlpha = _this.getClearAlpha();
  53996. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  53997. _this.clear();
  53998. if ( _renderBackground ) background.render( scene );
  53999. // Turn off the features which can affect the frag color for opaque objects pass.
  54000. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  54001. const currentToneMapping = _this.toneMapping;
  54002. _this.toneMapping = NoToneMapping;
  54003. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  54004. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  54005. const currentCameraViewport = camera.viewport;
  54006. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  54007. currentRenderState.setupLightsView( camera );
  54008. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  54009. renderObjects( opaqueObjects, scene, camera );
  54010. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  54011. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  54012. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  54013. let renderTargetNeedsUpdate = false;
  54014. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  54015. const renderItem = transmissiveObjects[ i ];
  54016. const { object, geometry, material, group } = renderItem;
  54017. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  54018. const currentSide = material.side;
  54019. material.side = BackSide;
  54020. material.needsUpdate = true;
  54021. renderObject( object, scene, camera, geometry, material, group );
  54022. material.side = currentSide;
  54023. material.needsUpdate = true;
  54024. renderTargetNeedsUpdate = true;
  54025. }
  54026. }
  54027. if ( renderTargetNeedsUpdate === true ) {
  54028. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  54029. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  54030. }
  54031. }
  54032. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  54033. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  54034. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  54035. _this.toneMapping = currentToneMapping;
  54036. }
  54037. function renderObjects( renderList, scene, camera ) {
  54038. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  54039. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  54040. const renderItem = renderList[ i ];
  54041. const { object, geometry, group } = renderItem;
  54042. let material = renderItem.material;
  54043. if ( material.allowOverride === true && overrideMaterial !== null ) {
  54044. material = overrideMaterial;
  54045. }
  54046. if ( object.layers.test( camera.layers ) ) {
  54047. renderObject( object, scene, camera, geometry, material, group );
  54048. }
  54049. }
  54050. }
  54051. function renderObject( object, scene, camera, geometry, material, group ) {
  54052. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  54053. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  54054. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  54055. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  54056. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  54057. material.side = BackSide;
  54058. material.needsUpdate = true;
  54059. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  54060. material.side = FrontSide;
  54061. material.needsUpdate = true;
  54062. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  54063. material.side = DoubleSide;
  54064. } else {
  54065. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  54066. }
  54067. object.onAfterRender( _this, scene, camera, geometry, material, group );
  54068. }
  54069. function getProgram( material, scene, object ) {
  54070. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  54071. const materialProperties = properties.get( material );
  54072. const lights = currentRenderState.state.lights;
  54073. const shadowsArray = currentRenderState.state.shadowsArray;
  54074. const lightsStateVersion = lights.state.version;
  54075. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  54076. const programCacheKey = programCache.getProgramCacheKey( parameters );
  54077. let programs = materialProperties.programs;
  54078. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  54079. materialProperties.environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null;
  54080. materialProperties.fog = scene.fog;
  54081. const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap );
  54082. materialProperties.envMap = environments.get( material.envMap || materialProperties.environment, usePMREM );
  54083. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  54084. if ( programs === undefined ) {
  54085. // new material
  54086. material.addEventListener( 'dispose', onMaterialDispose );
  54087. programs = new Map();
  54088. materialProperties.programs = programs;
  54089. }
  54090. let program = programs.get( programCacheKey );
  54091. if ( program !== undefined ) {
  54092. // early out if program and light state is identical
  54093. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  54094. updateCommonMaterialProperties( material, parameters );
  54095. return program;
  54096. }
  54097. } else {
  54098. parameters.uniforms = programCache.getUniforms( material );
  54099. material.onBeforeCompile( parameters, _this );
  54100. program = programCache.acquireProgram( parameters, programCacheKey );
  54101. programs.set( programCacheKey, program );
  54102. materialProperties.uniforms = parameters.uniforms;
  54103. }
  54104. const uniforms = materialProperties.uniforms;
  54105. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  54106. uniforms.clippingPlanes = clipping.uniform;
  54107. }
  54108. updateCommonMaterialProperties( material, parameters );
  54109. // store the light setup it was created for
  54110. materialProperties.needsLights = materialNeedsLights( material );
  54111. materialProperties.lightsStateVersion = lightsStateVersion;
  54112. if ( materialProperties.needsLights ) {
  54113. // wire up the material to this renderer's lighting state
  54114. uniforms.ambientLightColor.value = lights.state.ambient;
  54115. uniforms.lightProbe.value = lights.state.probe;
  54116. uniforms.directionalLights.value = lights.state.directional;
  54117. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  54118. uniforms.spotLights.value = lights.state.spot;
  54119. uniforms.spotLightShadows.value = lights.state.spotShadow;
  54120. uniforms.rectAreaLights.value = lights.state.rectArea;
  54121. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  54122. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  54123. uniforms.pointLights.value = lights.state.point;
  54124. uniforms.pointLightShadows.value = lights.state.pointShadow;
  54125. uniforms.hemisphereLights.value = lights.state.hemi;
  54126. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  54127. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  54128. uniforms.spotLightMap.value = lights.state.spotLightMap;
  54129. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  54130. // TODO (abelnation): add area lights shadow info to uniforms
  54131. }
  54132. materialProperties.currentProgram = program;
  54133. materialProperties.uniformsList = null;
  54134. return program;
  54135. }
  54136. function getUniformList( materialProperties ) {
  54137. if ( materialProperties.uniformsList === null ) {
  54138. const progUniforms = materialProperties.currentProgram.getUniforms();
  54139. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  54140. }
  54141. return materialProperties.uniformsList;
  54142. }
  54143. function updateCommonMaterialProperties( material, parameters ) {
  54144. const materialProperties = properties.get( material );
  54145. materialProperties.outputColorSpace = parameters.outputColorSpace;
  54146. materialProperties.batching = parameters.batching;
  54147. materialProperties.batchingColor = parameters.batchingColor;
  54148. materialProperties.instancing = parameters.instancing;
  54149. materialProperties.instancingColor = parameters.instancingColor;
  54150. materialProperties.instancingMorph = parameters.instancingMorph;
  54151. materialProperties.skinning = parameters.skinning;
  54152. materialProperties.morphTargets = parameters.morphTargets;
  54153. materialProperties.morphNormals = parameters.morphNormals;
  54154. materialProperties.morphColors = parameters.morphColors;
  54155. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  54156. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  54157. materialProperties.numIntersection = parameters.numClipIntersection;
  54158. materialProperties.vertexAlphas = parameters.vertexAlphas;
  54159. materialProperties.vertexTangents = parameters.vertexTangents;
  54160. materialProperties.toneMapping = parameters.toneMapping;
  54161. }
  54162. function setProgram( camera, scene, geometry, material, object ) {
  54163. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  54164. textures.resetTextureUnits();
  54165. const fog = scene.fog;
  54166. const environment = ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) ? scene.environment : null;
  54167. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  54168. const usePMREM = material.isMeshStandardMaterial || ( material.isMeshLambertMaterial && ! material.envMap ) || ( material.isMeshPhongMaterial && ! material.envMap );
  54169. const envMap = environments.get( material.envMap || environment, usePMREM );
  54170. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  54171. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  54172. const morphTargets = !! geometry.morphAttributes.position;
  54173. const morphNormals = !! geometry.morphAttributes.normal;
  54174. const morphColors = !! geometry.morphAttributes.color;
  54175. let toneMapping = NoToneMapping;
  54176. if ( material.toneMapped ) {
  54177. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  54178. toneMapping = _this.toneMapping;
  54179. }
  54180. }
  54181. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  54182. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  54183. const materialProperties = properties.get( material );
  54184. const lights = currentRenderState.state.lights;
  54185. if ( _clippingEnabled === true ) {
  54186. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  54187. const useCache =
  54188. camera === _currentCamera &&
  54189. material.id === _currentMaterialId;
  54190. // we might want to call this function with some ClippingGroup
  54191. // object instead of the material, once it becomes feasible
  54192. // (#8465, #8379)
  54193. clipping.setState( material, camera, useCache );
  54194. }
  54195. }
  54196. //
  54197. let needsProgramChange = false;
  54198. if ( material.version === materialProperties.__version ) {
  54199. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  54200. needsProgramChange = true;
  54201. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  54202. needsProgramChange = true;
  54203. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  54204. needsProgramChange = true;
  54205. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  54206. needsProgramChange = true;
  54207. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  54208. needsProgramChange = true;
  54209. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  54210. needsProgramChange = true;
  54211. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  54212. needsProgramChange = true;
  54213. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  54214. needsProgramChange = true;
  54215. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  54216. needsProgramChange = true;
  54217. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  54218. needsProgramChange = true;
  54219. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  54220. needsProgramChange = true;
  54221. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  54222. needsProgramChange = true;
  54223. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  54224. needsProgramChange = true;
  54225. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  54226. needsProgramChange = true;
  54227. } else if ( materialProperties.envMap !== envMap ) {
  54228. needsProgramChange = true;
  54229. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  54230. needsProgramChange = true;
  54231. } else if ( materialProperties.numClippingPlanes !== undefined &&
  54232. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  54233. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  54234. needsProgramChange = true;
  54235. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  54236. needsProgramChange = true;
  54237. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  54238. needsProgramChange = true;
  54239. } else if ( materialProperties.morphTargets !== morphTargets ) {
  54240. needsProgramChange = true;
  54241. } else if ( materialProperties.morphNormals !== morphNormals ) {
  54242. needsProgramChange = true;
  54243. } else if ( materialProperties.morphColors !== morphColors ) {
  54244. needsProgramChange = true;
  54245. } else if ( materialProperties.toneMapping !== toneMapping ) {
  54246. needsProgramChange = true;
  54247. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  54248. needsProgramChange = true;
  54249. }
  54250. } else {
  54251. needsProgramChange = true;
  54252. materialProperties.__version = material.version;
  54253. }
  54254. //
  54255. let program = materialProperties.currentProgram;
  54256. if ( needsProgramChange === true ) {
  54257. program = getProgram( material, scene, object );
  54258. }
  54259. let refreshProgram = false;
  54260. let refreshMaterial = false;
  54261. let refreshLights = false;
  54262. const p_uniforms = program.getUniforms(),
  54263. m_uniforms = materialProperties.uniforms;
  54264. if ( state.useProgram( program.program ) ) {
  54265. refreshProgram = true;
  54266. refreshMaterial = true;
  54267. refreshLights = true;
  54268. }
  54269. if ( material.id !== _currentMaterialId ) {
  54270. _currentMaterialId = material.id;
  54271. refreshMaterial = true;
  54272. }
  54273. if ( refreshProgram || _currentCamera !== camera ) {
  54274. // common camera uniforms
  54275. const reversedDepthBuffer = state.buffers.depth.getReversed();
  54276. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  54277. camera._reversedDepth = true;
  54278. camera.updateProjectionMatrix();
  54279. }
  54280. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  54281. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  54282. const uCamPos = p_uniforms.map.cameraPosition;
  54283. if ( uCamPos !== undefined ) {
  54284. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  54285. }
  54286. if ( capabilities.logarithmicDepthBuffer ) {
  54287. p_uniforms.setValue( _gl, 'logDepthBufFC',
  54288. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  54289. }
  54290. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  54291. if ( material.isMeshPhongMaterial ||
  54292. material.isMeshToonMaterial ||
  54293. material.isMeshLambertMaterial ||
  54294. material.isMeshBasicMaterial ||
  54295. material.isMeshStandardMaterial ||
  54296. material.isShaderMaterial ) {
  54297. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  54298. }
  54299. if ( _currentCamera !== camera ) {
  54300. _currentCamera = camera;
  54301. // lighting uniforms depend on the camera so enforce an update
  54302. // now, in case this material supports lights - or later, when
  54303. // the next material that does gets activated:
  54304. refreshMaterial = true; // set to true on material change
  54305. refreshLights = true; // remains set until update done
  54306. }
  54307. }
  54308. // Pre-allocate texture units for shadow samplers before setting data textures
  54309. if ( materialProperties.needsLights ) {
  54310. // Set shadow map uniforms first to ensure they get the first texture units
  54311. if ( lights.state.directionalShadowMap.length > 0 ) {
  54312. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  54313. }
  54314. if ( lights.state.spotShadowMap.length > 0 ) {
  54315. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  54316. }
  54317. if ( lights.state.pointShadowMap.length > 0 ) {
  54318. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  54319. }
  54320. }
  54321. // skinning and morph target uniforms must be set even if material didn't change
  54322. // auto-setting of texture unit for bone and morph texture must go before other textures
  54323. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  54324. if ( object.isSkinnedMesh ) {
  54325. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  54326. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  54327. const skeleton = object.skeleton;
  54328. if ( skeleton ) {
  54329. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  54330. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  54331. }
  54332. }
  54333. if ( object.isBatchedMesh ) {
  54334. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  54335. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  54336. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  54337. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  54338. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  54339. if ( object._colorsTexture !== null ) {
  54340. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  54341. }
  54342. }
  54343. const morphAttributes = geometry.morphAttributes;
  54344. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  54345. morphtargets.update( object, geometry, program );
  54346. }
  54347. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  54348. materialProperties.receiveShadow = object.receiveShadow;
  54349. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  54350. }
  54351. if ( ( material.isMeshStandardMaterial || material.isMeshLambertMaterial || material.isMeshPhongMaterial ) && material.envMap === null && scene.environment !== null ) {
  54352. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  54353. }
  54354. // Set DFG LUT for physically-based materials
  54355. if ( m_uniforms.dfgLUT !== undefined ) {
  54356. m_uniforms.dfgLUT.value = getDFGLUT();
  54357. }
  54358. if ( refreshMaterial ) {
  54359. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  54360. if ( materialProperties.needsLights ) {
  54361. // the current material requires lighting info
  54362. // note: all lighting uniforms are always set correctly
  54363. // they simply reference the renderer's state for their
  54364. // values
  54365. //
  54366. // use the current material's .needsUpdate flags to set
  54367. // the GL state when required
  54368. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  54369. }
  54370. // refresh uniforms common to several materials
  54371. if ( fog && material.fog === true ) {
  54372. materials.refreshFogUniforms( m_uniforms, fog );
  54373. }
  54374. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  54375. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54376. }
  54377. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  54378. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54379. material.uniformsNeedUpdate = false;
  54380. }
  54381. if ( material.isSpriteMaterial ) {
  54382. p_uniforms.setValue( _gl, 'center', object.center );
  54383. }
  54384. // common matrices
  54385. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  54386. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  54387. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  54388. // UBOs
  54389. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  54390. const groups = material.uniformsGroups;
  54391. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  54392. const group = groups[ i ];
  54393. uniformsGroups.update( group, program );
  54394. uniformsGroups.bind( group, program );
  54395. }
  54396. }
  54397. return program;
  54398. }
  54399. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  54400. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  54401. uniforms.ambientLightColor.needsUpdate = value;
  54402. uniforms.lightProbe.needsUpdate = value;
  54403. uniforms.directionalLights.needsUpdate = value;
  54404. uniforms.directionalLightShadows.needsUpdate = value;
  54405. uniforms.pointLights.needsUpdate = value;
  54406. uniforms.pointLightShadows.needsUpdate = value;
  54407. uniforms.spotLights.needsUpdate = value;
  54408. uniforms.spotLightShadows.needsUpdate = value;
  54409. uniforms.rectAreaLights.needsUpdate = value;
  54410. uniforms.hemisphereLights.needsUpdate = value;
  54411. }
  54412. function materialNeedsLights( material ) {
  54413. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  54414. material.isMeshStandardMaterial || material.isShadowMaterial ||
  54415. ( material.isShaderMaterial && material.lights === true );
  54416. }
  54417. /**
  54418. * Returns the active cube face.
  54419. *
  54420. * @return {number} The active cube face.
  54421. */
  54422. this.getActiveCubeFace = function () {
  54423. return _currentActiveCubeFace;
  54424. };
  54425. /**
  54426. * Returns the active mipmap level.
  54427. *
  54428. * @return {number} The active mipmap level.
  54429. */
  54430. this.getActiveMipmapLevel = function () {
  54431. return _currentActiveMipmapLevel;
  54432. };
  54433. /**
  54434. * Returns the active render target.
  54435. *
  54436. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  54437. * is currently set.
  54438. */
  54439. this.getRenderTarget = function () {
  54440. return _currentRenderTarget;
  54441. };
  54442. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  54443. const renderTargetProperties = properties.get( renderTarget );
  54444. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  54445. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  54446. // The multisample_render_to_texture extension doesn't work properly if there
  54447. // are midframe flushes and an external depth buffer. Disable use of the extension.
  54448. renderTargetProperties.__useRenderToTexture = false;
  54449. }
  54450. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  54451. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  54452. renderTargetProperties.__hasExternalTextures = true;
  54453. };
  54454. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  54455. const renderTargetProperties = properties.get( renderTarget );
  54456. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  54457. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  54458. };
  54459. const _scratchFrameBuffer = _gl.createFramebuffer();
  54460. /**
  54461. * Sets the active rendertarget.
  54462. *
  54463. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  54464. * the canvas is set as the active render target instead.
  54465. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  54466. * Indicates the z layer to render in to when using 3D or array render targets.
  54467. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  54468. */
  54469. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  54470. _currentRenderTarget = renderTarget;
  54471. _currentActiveCubeFace = activeCubeFace;
  54472. _currentActiveMipmapLevel = activeMipmapLevel;
  54473. let framebuffer = null;
  54474. let isCube = false;
  54475. let isRenderTarget3D = false;
  54476. if ( renderTarget ) {
  54477. const renderTargetProperties = properties.get( renderTarget );
  54478. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  54479. // Externally-managed framebuffer (e.g. XR)
  54480. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  54481. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  54482. _currentViewport.copy( renderTarget.viewport );
  54483. _currentScissor.copy( renderTarget.scissor );
  54484. _currentScissorTest = renderTarget.scissorTest;
  54485. state.viewport( _currentViewport );
  54486. state.scissor( _currentScissor );
  54487. state.setScissorTest( _currentScissorTest );
  54488. _currentMaterialId = -1;
  54489. return;
  54490. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  54491. textures.setupRenderTarget( renderTarget );
  54492. } else if ( renderTargetProperties.__hasExternalTextures ) {
  54493. // Color and depth texture must be rebound in order for the swapchain to update.
  54494. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  54495. } else if ( renderTarget.depthBuffer ) {
  54496. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  54497. const depthTexture = renderTarget.depthTexture;
  54498. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  54499. // check if the depth texture is compatible
  54500. if (
  54501. depthTexture !== null &&
  54502. properties.has( depthTexture ) &&
  54503. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  54504. ) {
  54505. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  54506. }
  54507. // Swap the depth buffer to the currently attached one
  54508. textures.setupDepthRenderbuffer( renderTarget );
  54509. }
  54510. }
  54511. const texture = renderTarget.texture;
  54512. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54513. isRenderTarget3D = true;
  54514. }
  54515. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54516. if ( renderTarget.isWebGLCubeRenderTarget ) {
  54517. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  54518. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  54519. } else {
  54520. framebuffer = __webglFramebuffer[ activeCubeFace ];
  54521. }
  54522. isCube = true;
  54523. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  54524. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  54525. } else {
  54526. if ( Array.isArray( __webglFramebuffer ) ) {
  54527. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  54528. } else {
  54529. framebuffer = __webglFramebuffer;
  54530. }
  54531. }
  54532. _currentViewport.copy( renderTarget.viewport );
  54533. _currentScissor.copy( renderTarget.scissor );
  54534. _currentScissorTest = renderTarget.scissorTest;
  54535. } else {
  54536. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  54537. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  54538. _currentScissorTest = _scissorTest;
  54539. }
  54540. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  54541. // being bound that are different sizes.
  54542. if ( activeMipmapLevel !== 0 ) {
  54543. framebuffer = _scratchFrameBuffer;
  54544. }
  54545. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54546. if ( framebufferBound ) {
  54547. state.drawBuffers( renderTarget, framebuffer );
  54548. }
  54549. state.viewport( _currentViewport );
  54550. state.scissor( _currentScissor );
  54551. state.setScissorTest( _currentScissorTest );
  54552. if ( isCube ) {
  54553. const textureProperties = properties.get( renderTarget.texture );
  54554. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  54555. } else if ( isRenderTarget3D ) {
  54556. const layer = activeCubeFace;
  54557. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  54558. const textureProperties = properties.get( renderTarget.textures[ i ] );
  54559. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  54560. }
  54561. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  54562. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  54563. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  54564. const textureProperties = properties.get( renderTarget.texture );
  54565. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  54566. }
  54567. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  54568. };
  54569. /**
  54570. * Reads the pixel data from the given render target into the given buffer.
  54571. *
  54572. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54573. * @param {number} x - The `x` coordinate of the copy region's origin.
  54574. * @param {number} y - The `y` coordinate of the copy region's origin.
  54575. * @param {number} width - The width of the copy region.
  54576. * @param {number} height - The height of the copy region.
  54577. * @param {TypedArray} buffer - The result buffer.
  54578. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54579. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54580. */
  54581. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54582. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54583. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54584. return;
  54585. }
  54586. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54587. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54588. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54589. }
  54590. if ( framebuffer ) {
  54591. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54592. try {
  54593. const texture = renderTarget.textures[ textureIndex ];
  54594. const textureFormat = texture.format;
  54595. const textureType = texture.type;
  54596. // when using MRT, select the correct color buffer for the subsequent read command
  54597. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54598. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54599. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  54600. return;
  54601. }
  54602. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54603. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54604. return;
  54605. }
  54606. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54607. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54608. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  54609. }
  54610. } finally {
  54611. // restore framebuffer of current render target if necessary
  54612. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54613. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54614. }
  54615. }
  54616. };
  54617. /**
  54618. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  54619. *
  54620. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  54621. *
  54622. * @async
  54623. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54624. * @param {number} x - The `x` coordinate of the copy region's origin.
  54625. * @param {number} y - The `y` coordinate of the copy region's origin.
  54626. * @param {number} width - The width of the copy region.
  54627. * @param {number} height - The height of the copy region.
  54628. * @param {TypedArray} buffer - The result buffer.
  54629. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54630. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54631. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54632. */
  54633. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54634. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54635. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54636. }
  54637. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54638. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54639. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54640. }
  54641. if ( framebuffer ) {
  54642. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54643. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54644. // set the active frame buffer to the one we want to read
  54645. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54646. const texture = renderTarget.textures[ textureIndex ];
  54647. const textureFormat = texture.format;
  54648. const textureType = texture.type;
  54649. // when using MRT, select the correct color buffer for the subsequent read command
  54650. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54651. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54652. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54653. }
  54654. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54655. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54656. }
  54657. const glBuffer = _gl.createBuffer();
  54658. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54659. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54660. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54661. // reset the frame buffer to the currently set buffer before waiting
  54662. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54663. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54664. // check if the commands have finished every 8 ms
  54665. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54666. _gl.flush();
  54667. await probeAsync( _gl, sync, 4 );
  54668. // read the data and delete the buffer
  54669. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54670. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54671. _gl.deleteBuffer( glBuffer );
  54672. _gl.deleteSync( sync );
  54673. return buffer;
  54674. } else {
  54675. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54676. }
  54677. }
  54678. };
  54679. /**
  54680. * Copies pixels from the current bound framebuffer into the given texture.
  54681. *
  54682. * @param {FramebufferTexture} texture - The texture.
  54683. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54684. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54685. */
  54686. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54687. const levelScale = Math.pow( 2, - level );
  54688. const width = Math.floor( texture.image.width * levelScale );
  54689. const height = Math.floor( texture.image.height * levelScale );
  54690. const x = position !== null ? position.x : 0;
  54691. const y = position !== null ? position.y : 0;
  54692. textures.setTexture2D( texture, 0 );
  54693. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54694. state.unbindTexture();
  54695. };
  54696. const _srcFramebuffer = _gl.createFramebuffer();
  54697. const _dstFramebuffer = _gl.createFramebuffer();
  54698. /**
  54699. * Copies data of the given source texture into a destination texture.
  54700. *
  54701. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54702. * {@link WebGLRenderer#initRenderTarget}.
  54703. *
  54704. * @param {Texture} srcTexture - The source texture.
  54705. * @param {Texture} dstTexture - The destination texture.
  54706. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54707. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54708. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54709. * @param {?number} [dstLevel=0] - The destination mipmap level.
  54710. */
  54711. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54712. // gather the necessary dimensions to copy
  54713. let width, height, depth, minX, minY, minZ;
  54714. let dstX, dstY, dstZ;
  54715. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54716. if ( srcRegion !== null ) {
  54717. width = srcRegion.max.x - srcRegion.min.x;
  54718. height = srcRegion.max.y - srcRegion.min.y;
  54719. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54720. minX = srcRegion.min.x;
  54721. minY = srcRegion.min.y;
  54722. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54723. } else {
  54724. const levelScale = Math.pow( 2, - srcLevel );
  54725. width = Math.floor( image.width * levelScale );
  54726. height = Math.floor( image.height * levelScale );
  54727. if ( srcTexture.isDataArrayTexture ) {
  54728. depth = image.depth;
  54729. } else if ( srcTexture.isData3DTexture ) {
  54730. depth = Math.floor( image.depth * levelScale );
  54731. } else {
  54732. depth = 1;
  54733. }
  54734. minX = 0;
  54735. minY = 0;
  54736. minZ = 0;
  54737. }
  54738. if ( dstPosition !== null ) {
  54739. dstX = dstPosition.x;
  54740. dstY = dstPosition.y;
  54741. dstZ = dstPosition.z;
  54742. } else {
  54743. dstX = 0;
  54744. dstY = 0;
  54745. dstZ = 0;
  54746. }
  54747. // Set up the destination target
  54748. const glFormat = utils.convert( dstTexture.format );
  54749. const glType = utils.convert( dstTexture.type );
  54750. let glTarget;
  54751. if ( dstTexture.isData3DTexture ) {
  54752. textures.setTexture3D( dstTexture, 0 );
  54753. glTarget = _gl.TEXTURE_3D;
  54754. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54755. textures.setTexture2DArray( dstTexture, 0 );
  54756. glTarget = _gl.TEXTURE_2D_ARRAY;
  54757. } else {
  54758. textures.setTexture2D( dstTexture, 0 );
  54759. glTarget = _gl.TEXTURE_2D;
  54760. }
  54761. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54762. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54763. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54764. // used for copying data from cpu
  54765. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54766. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54767. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54768. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54769. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54770. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54771. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54772. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54773. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54774. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54775. // set up the src texture
  54776. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54777. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54778. if ( srcTexture.isDepthTexture ) {
  54779. const srcTextureProperties = properties.get( srcTexture );
  54780. const dstTextureProperties = properties.get( dstTexture );
  54781. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54782. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54783. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54784. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54785. for ( let i = 0; i < depth; i ++ ) {
  54786. // if the source or destination are a 3d target then a layer needs to be bound
  54787. if ( isSrc3D ) {
  54788. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54789. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54790. }
  54791. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54792. }
  54793. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54794. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54795. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54796. // get the appropriate frame buffers
  54797. const srcTextureProperties = properties.get( srcTexture );
  54798. const dstTextureProperties = properties.get( dstTexture );
  54799. // bind the frame buffer targets
  54800. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54801. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54802. for ( let i = 0; i < depth; i ++ ) {
  54803. // assign the correct layers and mip maps to the frame buffers
  54804. if ( isSrc3D ) {
  54805. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54806. } else {
  54807. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54808. }
  54809. if ( isDst3D ) {
  54810. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54811. } else {
  54812. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54813. }
  54814. // copy the data using the fastest function that can achieve the copy
  54815. if ( srcLevel !== 0 ) {
  54816. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54817. } else if ( isDst3D ) {
  54818. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54819. } else {
  54820. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54821. }
  54822. }
  54823. // unbind read, draw buffers
  54824. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54825. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54826. } else {
  54827. if ( isDst3D ) {
  54828. // copy data into the 3d texture
  54829. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54830. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54831. } else if ( dstTexture.isCompressedArrayTexture ) {
  54832. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54833. } else {
  54834. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54835. }
  54836. } else {
  54837. // copy data into the 2d texture
  54838. if ( srcTexture.isDataTexture ) {
  54839. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54840. } else if ( srcTexture.isCompressedTexture ) {
  54841. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54842. } else {
  54843. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54844. }
  54845. }
  54846. }
  54847. // reset values
  54848. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54849. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54850. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54851. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54852. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54853. // Generate mipmaps only when copying level 0
  54854. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54855. _gl.generateMipmap( glTarget );
  54856. }
  54857. state.unbindTexture();
  54858. };
  54859. /**
  54860. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54861. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54862. * rendered to.
  54863. *
  54864. * @param {WebGLRenderTarget} target - The render target.
  54865. */
  54866. this.initRenderTarget = function ( target ) {
  54867. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54868. textures.setupRenderTarget( target );
  54869. }
  54870. };
  54871. /**
  54872. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54873. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54874. *
  54875. * @param {Texture} texture - The texture.
  54876. */
  54877. this.initTexture = function ( texture ) {
  54878. if ( texture.isCubeTexture ) {
  54879. textures.setTextureCube( texture, 0 );
  54880. } else if ( texture.isData3DTexture ) {
  54881. textures.setTexture3D( texture, 0 );
  54882. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54883. textures.setTexture2DArray( texture, 0 );
  54884. } else {
  54885. textures.setTexture2D( texture, 0 );
  54886. }
  54887. state.unbindTexture();
  54888. };
  54889. /**
  54890. * Can be used to reset the internal WebGL state. This method is mostly
  54891. * relevant for applications which share a single WebGL context across
  54892. * multiple WebGL libraries.
  54893. */
  54894. this.resetState = function () {
  54895. _currentActiveCubeFace = 0;
  54896. _currentActiveMipmapLevel = 0;
  54897. _currentRenderTarget = null;
  54898. state.reset();
  54899. bindingStates.reset();
  54900. };
  54901. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54902. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54903. }
  54904. }
  54905. /**
  54906. * Defines the coordinate system of the renderer.
  54907. *
  54908. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54909. *
  54910. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54911. * @default WebGLCoordinateSystem
  54912. * @readonly
  54913. */
  54914. get coordinateSystem() {
  54915. return WebGLCoordinateSystem;
  54916. }
  54917. /**
  54918. * Defines the output color space of the renderer.
  54919. *
  54920. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54921. * @default SRGBColorSpace
  54922. */
  54923. get outputColorSpace() {
  54924. return this._outputColorSpace;
  54925. }
  54926. set outputColorSpace( colorSpace ) {
  54927. this._outputColorSpace = colorSpace;
  54928. const gl = this.getContext();
  54929. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54930. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54931. }
  54932. }
  54933. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  54934. exports.AddEquation = AddEquation;
  54935. exports.AddOperation = AddOperation;
  54936. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  54937. exports.AdditiveBlending = AdditiveBlending;
  54938. exports.AgXToneMapping = AgXToneMapping;
  54939. exports.AlphaFormat = AlphaFormat;
  54940. exports.AlwaysCompare = AlwaysCompare;
  54941. exports.AlwaysDepth = AlwaysDepth;
  54942. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  54943. exports.AmbientLight = AmbientLight;
  54944. exports.AnimationAction = AnimationAction;
  54945. exports.AnimationClip = AnimationClip;
  54946. exports.AnimationLoader = AnimationLoader;
  54947. exports.AnimationMixer = AnimationMixer;
  54948. exports.AnimationObjectGroup = AnimationObjectGroup;
  54949. exports.AnimationUtils = AnimationUtils;
  54950. exports.ArcCurve = ArcCurve;
  54951. exports.ArrayCamera = ArrayCamera;
  54952. exports.ArrowHelper = ArrowHelper;
  54953. exports.AttachedBindMode = AttachedBindMode;
  54954. exports.Audio = Audio;
  54955. exports.AudioAnalyser = AudioAnalyser;
  54956. exports.AudioContext = AudioContext;
  54957. exports.AudioListener = AudioListener;
  54958. exports.AudioLoader = AudioLoader;
  54959. exports.AxesHelper = AxesHelper;
  54960. exports.BackSide = BackSide;
  54961. exports.BasicDepthPacking = BasicDepthPacking;
  54962. exports.BasicShadowMap = BasicShadowMap;
  54963. exports.BatchedMesh = BatchedMesh;
  54964. exports.BezierInterpolant = BezierInterpolant;
  54965. exports.Bone = Bone;
  54966. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  54967. exports.Box2 = Box2;
  54968. exports.Box3 = Box3;
  54969. exports.Box3Helper = Box3Helper;
  54970. exports.BoxGeometry = BoxGeometry;
  54971. exports.BoxHelper = BoxHelper;
  54972. exports.BufferAttribute = BufferAttribute;
  54973. exports.BufferGeometry = BufferGeometry;
  54974. exports.BufferGeometryLoader = BufferGeometryLoader;
  54975. exports.ByteType = ByteType;
  54976. exports.Cache = Cache;
  54977. exports.Camera = Camera;
  54978. exports.CameraHelper = CameraHelper;
  54979. exports.CanvasTexture = CanvasTexture;
  54980. exports.CapsuleGeometry = CapsuleGeometry;
  54981. exports.CatmullRomCurve3 = CatmullRomCurve3;
  54982. exports.CineonToneMapping = CineonToneMapping;
  54983. exports.CircleGeometry = CircleGeometry;
  54984. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  54985. exports.Clock = Clock;
  54986. exports.Color = Color;
  54987. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  54988. exports.ColorManagement = ColorManagement;
  54989. exports.Compatibility = Compatibility;
  54990. exports.CompressedArrayTexture = CompressedArrayTexture;
  54991. exports.CompressedCubeTexture = CompressedCubeTexture;
  54992. exports.CompressedTexture = CompressedTexture;
  54993. exports.CompressedTextureLoader = CompressedTextureLoader;
  54994. exports.ConeGeometry = ConeGeometry;
  54995. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  54996. exports.ConstantColorFactor = ConstantColorFactor;
  54997. exports.Controls = Controls;
  54998. exports.CubeCamera = CubeCamera;
  54999. exports.CubeDepthTexture = CubeDepthTexture;
  55000. exports.CubeReflectionMapping = CubeReflectionMapping;
  55001. exports.CubeRefractionMapping = CubeRefractionMapping;
  55002. exports.CubeTexture = CubeTexture;
  55003. exports.CubeTextureLoader = CubeTextureLoader;
  55004. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  55005. exports.CubicBezierCurve = CubicBezierCurve;
  55006. exports.CubicBezierCurve3 = CubicBezierCurve3;
  55007. exports.CubicInterpolant = CubicInterpolant;
  55008. exports.CullFaceBack = CullFaceBack;
  55009. exports.CullFaceFront = CullFaceFront;
  55010. exports.CullFaceFrontBack = CullFaceFrontBack;
  55011. exports.CullFaceNone = CullFaceNone;
  55012. exports.Curve = Curve;
  55013. exports.CurvePath = CurvePath;
  55014. exports.CustomBlending = CustomBlending;
  55015. exports.CustomToneMapping = CustomToneMapping;
  55016. exports.CylinderGeometry = CylinderGeometry;
  55017. exports.Cylindrical = Cylindrical;
  55018. exports.Data3DTexture = Data3DTexture;
  55019. exports.DataArrayTexture = DataArrayTexture;
  55020. exports.DataTexture = DataTexture;
  55021. exports.DataTextureLoader = DataTextureLoader;
  55022. exports.DataUtils = DataUtils;
  55023. exports.DecrementStencilOp = DecrementStencilOp;
  55024. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  55025. exports.DefaultLoadingManager = DefaultLoadingManager;
  55026. exports.DepthFormat = DepthFormat;
  55027. exports.DepthStencilFormat = DepthStencilFormat;
  55028. exports.DepthTexture = DepthTexture;
  55029. exports.DetachedBindMode = DetachedBindMode;
  55030. exports.DirectionalLight = DirectionalLight;
  55031. exports.DirectionalLightHelper = DirectionalLightHelper;
  55032. exports.DiscreteInterpolant = DiscreteInterpolant;
  55033. exports.DodecahedronGeometry = DodecahedronGeometry;
  55034. exports.DoubleSide = DoubleSide;
  55035. exports.DstAlphaFactor = DstAlphaFactor;
  55036. exports.DstColorFactor = DstColorFactor;
  55037. exports.DynamicCopyUsage = DynamicCopyUsage;
  55038. exports.DynamicDrawUsage = DynamicDrawUsage;
  55039. exports.DynamicReadUsage = DynamicReadUsage;
  55040. exports.EdgesGeometry = EdgesGeometry;
  55041. exports.EllipseCurve = EllipseCurve;
  55042. exports.EqualCompare = EqualCompare;
  55043. exports.EqualDepth = EqualDepth;
  55044. exports.EqualStencilFunc = EqualStencilFunc;
  55045. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  55046. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  55047. exports.Euler = Euler;
  55048. exports.EventDispatcher = EventDispatcher;
  55049. exports.ExternalTexture = ExternalTexture;
  55050. exports.ExtrudeGeometry = ExtrudeGeometry;
  55051. exports.FileLoader = FileLoader;
  55052. exports.Float16BufferAttribute = Float16BufferAttribute;
  55053. exports.Float32BufferAttribute = Float32BufferAttribute;
  55054. exports.FloatType = FloatType;
  55055. exports.Fog = Fog;
  55056. exports.FogExp2 = FogExp2;
  55057. exports.FramebufferTexture = FramebufferTexture;
  55058. exports.FrontSide = FrontSide;
  55059. exports.Frustum = Frustum;
  55060. exports.FrustumArray = FrustumArray;
  55061. exports.GLBufferAttribute = GLBufferAttribute;
  55062. exports.GLSL1 = GLSL1;
  55063. exports.GLSL3 = GLSL3;
  55064. exports.GreaterCompare = GreaterCompare;
  55065. exports.GreaterDepth = GreaterDepth;
  55066. exports.GreaterEqualCompare = GreaterEqualCompare;
  55067. exports.GreaterEqualDepth = GreaterEqualDepth;
  55068. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  55069. exports.GreaterStencilFunc = GreaterStencilFunc;
  55070. exports.GridHelper = GridHelper;
  55071. exports.Group = Group;
  55072. exports.HalfFloatType = HalfFloatType;
  55073. exports.HemisphereLight = HemisphereLight;
  55074. exports.HemisphereLightHelper = HemisphereLightHelper;
  55075. exports.IcosahedronGeometry = IcosahedronGeometry;
  55076. exports.ImageBitmapLoader = ImageBitmapLoader;
  55077. exports.ImageLoader = ImageLoader;
  55078. exports.ImageUtils = ImageUtils;
  55079. exports.IncrementStencilOp = IncrementStencilOp;
  55080. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  55081. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  55082. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  55083. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  55084. exports.InstancedMesh = InstancedMesh;
  55085. exports.Int16BufferAttribute = Int16BufferAttribute;
  55086. exports.Int32BufferAttribute = Int32BufferAttribute;
  55087. exports.Int8BufferAttribute = Int8BufferAttribute;
  55088. exports.IntType = IntType;
  55089. exports.InterleavedBuffer = InterleavedBuffer;
  55090. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  55091. exports.Interpolant = Interpolant;
  55092. exports.InterpolateBezier = InterpolateBezier;
  55093. exports.InterpolateDiscrete = InterpolateDiscrete;
  55094. exports.InterpolateLinear = InterpolateLinear;
  55095. exports.InterpolateSmooth = InterpolateSmooth;
  55096. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  55097. exports.InterpolationSamplingType = InterpolationSamplingType;
  55098. exports.InvertStencilOp = InvertStencilOp;
  55099. exports.KeepStencilOp = KeepStencilOp;
  55100. exports.KeyframeTrack = KeyframeTrack;
  55101. exports.LOD = LOD;
  55102. exports.LatheGeometry = LatheGeometry;
  55103. exports.Layers = Layers;
  55104. exports.LessCompare = LessCompare;
  55105. exports.LessDepth = LessDepth;
  55106. exports.LessEqualCompare = LessEqualCompare;
  55107. exports.LessEqualDepth = LessEqualDepth;
  55108. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  55109. exports.LessStencilFunc = LessStencilFunc;
  55110. exports.Light = Light;
  55111. exports.LightProbe = LightProbe;
  55112. exports.Line = Line;
  55113. exports.Line3 = Line3;
  55114. exports.LineBasicMaterial = LineBasicMaterial;
  55115. exports.LineCurve = LineCurve;
  55116. exports.LineCurve3 = LineCurve3;
  55117. exports.LineDashedMaterial = LineDashedMaterial;
  55118. exports.LineLoop = LineLoop;
  55119. exports.LineSegments = LineSegments;
  55120. exports.LinearFilter = LinearFilter;
  55121. exports.LinearInterpolant = LinearInterpolant;
  55122. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  55123. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  55124. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  55125. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  55126. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  55127. exports.LinearToneMapping = LinearToneMapping;
  55128. exports.LinearTransfer = LinearTransfer;
  55129. exports.Loader = Loader;
  55130. exports.LoaderUtils = LoaderUtils;
  55131. exports.LoadingManager = LoadingManager;
  55132. exports.LoopOnce = LoopOnce;
  55133. exports.LoopPingPong = LoopPingPong;
  55134. exports.LoopRepeat = LoopRepeat;
  55135. exports.MOUSE = MOUSE;
  55136. exports.Material = Material;
  55137. exports.MaterialBlending = MaterialBlending;
  55138. exports.MaterialLoader = MaterialLoader;
  55139. exports.MathUtils = MathUtils;
  55140. exports.Matrix2 = Matrix2;
  55141. exports.Matrix3 = Matrix3;
  55142. exports.Matrix4 = Matrix4;
  55143. exports.MaxEquation = MaxEquation;
  55144. exports.Mesh = Mesh;
  55145. exports.MeshBasicMaterial = MeshBasicMaterial;
  55146. exports.MeshDepthMaterial = MeshDepthMaterial;
  55147. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  55148. exports.MeshLambertMaterial = MeshLambertMaterial;
  55149. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  55150. exports.MeshNormalMaterial = MeshNormalMaterial;
  55151. exports.MeshPhongMaterial = MeshPhongMaterial;
  55152. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  55153. exports.MeshStandardMaterial = MeshStandardMaterial;
  55154. exports.MeshToonMaterial = MeshToonMaterial;
  55155. exports.MinEquation = MinEquation;
  55156. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  55157. exports.MixOperation = MixOperation;
  55158. exports.MultiplyBlending = MultiplyBlending;
  55159. exports.MultiplyOperation = MultiplyOperation;
  55160. exports.NearestFilter = NearestFilter;
  55161. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  55162. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  55163. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  55164. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  55165. exports.NeutralToneMapping = NeutralToneMapping;
  55166. exports.NeverCompare = NeverCompare;
  55167. exports.NeverDepth = NeverDepth;
  55168. exports.NeverStencilFunc = NeverStencilFunc;
  55169. exports.NoBlending = NoBlending;
  55170. exports.NoColorSpace = NoColorSpace;
  55171. exports.NoNormalPacking = NoNormalPacking;
  55172. exports.NoToneMapping = NoToneMapping;
  55173. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  55174. exports.NormalBlending = NormalBlending;
  55175. exports.NormalGAPacking = NormalGAPacking;
  55176. exports.NormalRGPacking = NormalRGPacking;
  55177. exports.NotEqualCompare = NotEqualCompare;
  55178. exports.NotEqualDepth = NotEqualDepth;
  55179. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  55180. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  55181. exports.Object3D = Object3D;
  55182. exports.ObjectLoader = ObjectLoader;
  55183. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  55184. exports.OctahedronGeometry = OctahedronGeometry;
  55185. exports.OneFactor = OneFactor;
  55186. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  55187. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  55188. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  55189. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  55190. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  55191. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  55192. exports.OrthographicCamera = OrthographicCamera;
  55193. exports.PCFShadowMap = PCFShadowMap;
  55194. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  55195. exports.PMREMGenerator = PMREMGenerator;
  55196. exports.Path = Path;
  55197. exports.PerspectiveCamera = PerspectiveCamera;
  55198. exports.Plane = Plane;
  55199. exports.PlaneGeometry = PlaneGeometry;
  55200. exports.PlaneHelper = PlaneHelper;
  55201. exports.PointLight = PointLight;
  55202. exports.PointLightHelper = PointLightHelper;
  55203. exports.Points = Points;
  55204. exports.PointsMaterial = PointsMaterial;
  55205. exports.PolarGridHelper = PolarGridHelper;
  55206. exports.PolyhedronGeometry = PolyhedronGeometry;
  55207. exports.PositionalAudio = PositionalAudio;
  55208. exports.PropertyBinding = PropertyBinding;
  55209. exports.PropertyMixer = PropertyMixer;
  55210. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  55211. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  55212. exports.Quaternion = Quaternion;
  55213. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  55214. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  55215. exports.R11_EAC_Format = R11_EAC_Format;
  55216. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  55217. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  55218. exports.REVISION = REVISION;
  55219. exports.RG11_EAC_Format = RG11_EAC_Format;
  55220. exports.RGBADepthPacking = RGBADepthPacking;
  55221. exports.RGBAFormat = RGBAFormat;
  55222. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  55223. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  55224. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  55225. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  55226. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  55227. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  55228. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  55229. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  55230. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  55231. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  55232. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  55233. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  55234. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  55235. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  55236. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  55237. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  55238. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  55239. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  55240. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  55241. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  55242. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  55243. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  55244. exports.RGBDepthPacking = RGBDepthPacking;
  55245. exports.RGBFormat = RGBFormat;
  55246. exports.RGBIntegerFormat = RGBIntegerFormat;
  55247. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  55248. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  55249. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  55250. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  55251. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  55252. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  55253. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  55254. exports.RGDepthPacking = RGDepthPacking;
  55255. exports.RGFormat = RGFormat;
  55256. exports.RGIntegerFormat = RGIntegerFormat;
  55257. exports.RawShaderMaterial = RawShaderMaterial;
  55258. exports.Ray = Ray;
  55259. exports.Raycaster = Raycaster;
  55260. exports.RectAreaLight = RectAreaLight;
  55261. exports.RedFormat = RedFormat;
  55262. exports.RedIntegerFormat = RedIntegerFormat;
  55263. exports.ReinhardToneMapping = ReinhardToneMapping;
  55264. exports.RenderTarget = RenderTarget;
  55265. exports.RenderTarget3D = RenderTarget3D;
  55266. exports.RepeatWrapping = RepeatWrapping;
  55267. exports.ReplaceStencilOp = ReplaceStencilOp;
  55268. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  55269. exports.RingGeometry = RingGeometry;
  55270. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  55271. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  55272. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  55273. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  55274. exports.SRGBColorSpace = SRGBColorSpace;
  55275. exports.SRGBTransfer = SRGBTransfer;
  55276. exports.Scene = Scene;
  55277. exports.ShaderChunk = ShaderChunk;
  55278. exports.ShaderLib = ShaderLib;
  55279. exports.ShaderMaterial = ShaderMaterial;
  55280. exports.ShadowMaterial = ShadowMaterial;
  55281. exports.Shape = Shape;
  55282. exports.ShapeGeometry = ShapeGeometry;
  55283. exports.ShapePath = ShapePath;
  55284. exports.ShapeUtils = ShapeUtils;
  55285. exports.ShortType = ShortType;
  55286. exports.Skeleton = Skeleton;
  55287. exports.SkeletonHelper = SkeletonHelper;
  55288. exports.SkinnedMesh = SkinnedMesh;
  55289. exports.Source = Source;
  55290. exports.Sphere = Sphere;
  55291. exports.SphereGeometry = SphereGeometry;
  55292. exports.Spherical = Spherical;
  55293. exports.SphericalHarmonics3 = SphericalHarmonics3;
  55294. exports.SplineCurve = SplineCurve;
  55295. exports.SpotLight = SpotLight;
  55296. exports.SpotLightHelper = SpotLightHelper;
  55297. exports.Sprite = Sprite;
  55298. exports.SpriteMaterial = SpriteMaterial;
  55299. exports.SrcAlphaFactor = SrcAlphaFactor;
  55300. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  55301. exports.SrcColorFactor = SrcColorFactor;
  55302. exports.StaticCopyUsage = StaticCopyUsage;
  55303. exports.StaticDrawUsage = StaticDrawUsage;
  55304. exports.StaticReadUsage = StaticReadUsage;
  55305. exports.StereoCamera = StereoCamera;
  55306. exports.StreamCopyUsage = StreamCopyUsage;
  55307. exports.StreamDrawUsage = StreamDrawUsage;
  55308. exports.StreamReadUsage = StreamReadUsage;
  55309. exports.StringKeyframeTrack = StringKeyframeTrack;
  55310. exports.SubtractEquation = SubtractEquation;
  55311. exports.SubtractiveBlending = SubtractiveBlending;
  55312. exports.TOUCH = TOUCH;
  55313. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  55314. exports.TetrahedronGeometry = TetrahedronGeometry;
  55315. exports.Texture = Texture;
  55316. exports.TextureLoader = TextureLoader;
  55317. exports.TextureUtils = TextureUtils;
  55318. exports.Timer = Timer;
  55319. exports.TimestampQuery = TimestampQuery;
  55320. exports.TorusGeometry = TorusGeometry;
  55321. exports.TorusKnotGeometry = TorusKnotGeometry;
  55322. exports.Triangle = Triangle;
  55323. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  55324. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  55325. exports.TrianglesDrawMode = TrianglesDrawMode;
  55326. exports.TubeGeometry = TubeGeometry;
  55327. exports.UVMapping = UVMapping;
  55328. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  55329. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  55330. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  55331. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  55332. exports.Uniform = Uniform;
  55333. exports.UniformsGroup = UniformsGroup;
  55334. exports.UniformsLib = UniformsLib;
  55335. exports.UniformsUtils = UniformsUtils;
  55336. exports.UnsignedByteType = UnsignedByteType;
  55337. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  55338. exports.UnsignedInt248Type = UnsignedInt248Type;
  55339. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  55340. exports.UnsignedIntType = UnsignedIntType;
  55341. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  55342. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  55343. exports.UnsignedShortType = UnsignedShortType;
  55344. exports.VSMShadowMap = VSMShadowMap;
  55345. exports.Vector2 = Vector2;
  55346. exports.Vector3 = Vector3;
  55347. exports.Vector4 = Vector4;
  55348. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  55349. exports.VideoFrameTexture = VideoFrameTexture;
  55350. exports.VideoTexture = VideoTexture;
  55351. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  55352. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  55353. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  55354. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  55355. exports.WebGLRenderTarget = WebGLRenderTarget;
  55356. exports.WebGLRenderer = WebGLRenderer;
  55357. exports.WebGLUtils = WebGLUtils;
  55358. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  55359. exports.WebXRController = WebXRController;
  55360. exports.WireframeGeometry = WireframeGeometry;
  55361. exports.WrapAroundEnding = WrapAroundEnding;
  55362. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  55363. exports.ZeroFactor = ZeroFactor;
  55364. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  55365. exports.ZeroStencilOp = ZeroStencilOp;
  55366. exports.createCanvasElement = createCanvasElement;
  55367. exports.error = error;
  55368. exports.getConsoleFunction = getConsoleFunction;
  55369. exports.log = log;
  55370. exports.setConsoleFunction = setConsoleFunction;
  55371. exports.warn = warn;
  55372. exports.warnOnce = warnOnce;
粤ICP备19079148号